相信很多網頁開發者都會處理到在建立一個新的網站被小小的NGINX Rewrite設定花了一天的時間再處理,每次專案初始化設定時,往往都會花掉不少時間,而且由於PHP的框架眾多,我目前只提供日常比較常用的框架設定供你參考,我也順便紀錄下來當作備忘錄,也希望藉由此次分享讓開發者能更快掌握相關語法。
常見的Framework Rewrite規則:
Laravel
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
Codeigniter(CI)
location / {
try_files $uri $uri/ /index.php;
}
Discuz
location / {
rewrite ^/archiver/((fid|tid)-[\w\-]+\.html)$ /archiver/index.php?$1 last;
rewrite ^/forum-([0-9]+)-([0-9]+)\.html$ /forumdisplay.php?fid=$1&page=$2 last;
rewrite ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /viewthread.php?tid=$1&extra=page%3D$3&page=$2 last;
rewrite ^/space-(username|uid)-(.+)\.html$ /space.php?$1=$2 last;
rewrite ^/tag-(.+)\.html$ /tag.php?name=$1 last;
}
Joomla
location / {
try_files $uri $uri/ /index.php;
}
Drupal
location / {
try_files $uri $uri/ /index.php;
}
WordPress
location / {
try_files $uri $uri/ /index.php?$args;
}
WordPress(如果是虛擬目錄)
假設你有個Wordpress網站原來是blog.abc.com,因為某些原因,你需要調整成abc.com/blog/,你就需要在nginx站台設定中abc.com的設定檔案加入以下設定
location /blog/ {
alias /var/www/blog/;
try_files $uri $uri/ /blog/index.php?$args;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass 127.0.0.1:9000;
}
}
if (!-e $request_filename)
{
rewrite ^/(.*)$ /blog/index.php?/$1 last;
break;
}
ThinkPhp
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
}
Vue
location / {
try_files $uri $uri/ /index.html;
}
Reference
- nginx官方網站-Wordpress:https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/
- nginx官方網站-Drupal:https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
- nginx官方網站-CI:https://www.nginx.com/resources/wiki/start/topics/recipes/codeigniter/
- Nginx location match tester(語法驗證工具):https://nginx.viraptor.info/
- nginx playground(語法測試工具):https://nginx-playground.wizardzines.com/

你好,我是RD爸,希望透過我的紀錄,可以帶給你一些新的想法~ 專注於各式3C產品的開箱評測、程式相關技術及理財筆記。
email ►[email protected]