在 Nginx 上啟用 WordPress 固定網址功能

本來我的設定檔只有寫了

location ~* .php$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

所以不能啟用固定網址,只能傻傻地用 index.php?p=xxx
不過照著 WordPress Codex: http://codex.wordpress.org/Nginx 做之後不知道為什麼會一直變成下載

於是 雪人大大提供了他的設定檔:

location / {
    # unless the request is for a valid file, send to bootstrap
    if (!-e $request_filename) {
        rewrite ^(.+)$ /index.php?q=$1 last;
    }
}

location ~ ^(.+.php)(.)$ {
    fastcgi_split_path_info ^(.+.php)(.)$;
    try_files $uri =404;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    include fastcgi_params;
}

於是我改改之後變成了一個比官網更快設定的方法,

location / {
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^(.+)$ /index.php last;
}

location ~* .php$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

因為 if is evil 所以改用 @rewrite 來實作,先檢查檔案不存在就 rewrite
rewrite 不直接 try_files index.php?$args 的好處是 WordPress 還是可以拿到目前的網址,這樣就連參數都不用傳送了 XDDDDDD