laravel學習之nginx配置站點

前言

設置laravel項目的域名站點的時候,須要對nginx作一些對應的重寫rewrite配置,用來作相關路由,不然會報404。php

nginx.conf配置

server {
    listen 80;
    server_name xxx.com;  #域名
    root /data/www/myProject/blog/public;  #站點目錄,請求到laravel項目的public目錄
    index index.html index.htm index.php;  #默認請求的文件
    
    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000; 
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name; 
             
            include        fastcgi_params;
    }
    
    
    location / {
        try_files $uri $uri/ /index.php?$query_string; # 這一句是laravel部署必須的,將index.php隱藏掉
    }

    if (!-d $request_filename)
    {
        rewrite ^/(.+)/$ /$1 permanent;
    }

    # 去除index action
    if ($request_uri ~* index/?$)
    {
        rewrite ^/(.*)/index/?$ /$1 permanent;
    }

    # 根據laravel規則進行url重寫
    if (!-e $request_filename)
    {
          rewrite ^/(.*)$ /index.php?/$1 last;
          break;
    }
    location = /50x.html {
          root   html;
    }
}

操做及實例

  1. 對nginx.conf重寫站點後,要重啓nginx:html

    sudo nginx -s reload
  2. 以laravel5.2版本爲例,模擬輸出hello world,能夠在laravel項目中app/Http/routes.php中定義一個hello的路由:nginx

    Route::get('/hello', function(){
         return 'hello world';
     });
  3. 瀏覽器輸入xxx.com/hello便可在瀏覽器打印出hello world
相關文章
相關標籤/搜索