前言
設定laravel專案的域名站點的時候,需要對nginx做一些對應的重寫rewrite配置,用來做相關路由,否則會報404。
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;
}
}
操作及例項
-
對nginx.conf重寫站點後,要重啟nginx:
sudo nginx -s reload
-
以laravel5.2版本為例,模擬輸出hello world,可以在laravel專案中app/Http/routes.php中定義一個hello的路由:
Route::get(`/hello`, function(){ return `hello world`; });
- 瀏覽器輸入xxx.com/hello即可在瀏覽器列印出hello world