相信大家都知道 Nginx 搭配 PHP-FPM 用起來效能還不錯,這次來筆記如何設定 Nginx 去除 PHP MVC Framework 討厭的 index.php 字符串,不管是 Laravel 或 CodeIgniter 教學文件都是在 Apache 設定 .htaccess 來達成 Cleaner URL,Apache 最大好處支持 .htaccess,但是 Nginx 也有強大的效能,此篇紀錄如何設定 Nginx 達成 mod_rewrite 效果。
首先來看看 apache .htaccess 是如何設定:
<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]</IfModule>
上面的意思就是代表如果該 URL 是不存在的檔案或者是目錄就全部導向 index.php,如果在 Ubuntu 底下可能會產生 Loop,請把 .htaccess 改成底下
Options +FollowSymLinksRewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . index.php [L]
接著 Nginx 是如何設定呢?打開html' target='_blank'>虛擬主機設定文件 /etc/nginx/sites-available/xxxx,將底下設定寫入
server { listen 80; server_name laravel.wuboy.twbbs.org; root /usr/home/git/laravel/public; access_log /var/log/nginx/laravel_access.log; error_log /var/log/nginx/laravel_error.log; location / { index index.php index.html index.htm; } if ($request_uri ~* index/?$) { rewrite ^/(.*)/index/?$ /$1 permanent; } # removes trailing slashes (prevents SEO duplicate content issues) if (!-d $request_filename) { rewrite ^/(.+)/$ /$1 permanent; } # removes access to "system" folder, also allows a "System.php" controller if ($request_uri ~* ^/system) { rewrite ^/(.*)$ /index.php?/$1 last; break; } # unless the request is for a valid file (image, js, css, etc.), send to bootstrap if (!-e $request_filename) { rewrite ^/(.*)$ /index.php?/$1 last; break; } # catch all error_page 404 /index.php; # use fastcgi for all php files location ~ /.php$ { fastcgi_pass unix:/tmp/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /usr/local/etc/nginx/fastcgi_params; fastcgi_param HTTPS off; } # deny access to apache .htaccess files location ~ //.ht { deny all; }}
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答
圖片精選