第一次接觸 nginx 時,頁面本身跑得還行,速度也不差,但 CSS 和 JS 完全載不進來,畫面像被扒了一層皮。原因在於 nginx 需要為不同類型的檔案分別設定處理規則——它不會像 Apache 那樣靠 .htaccess 自動猜,所有路徑都掉進同一個 rewrite 裡,靜態資源自然被 PHP 吃掉了。
想通之後其實很有道理。以下是可以直接參考的設定:
#user nobody;
worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
access_log logs/access.log;
sendfile on;
keepalive_timeout 65;
server {
listen 8081 default;
server_name localhost;
charset utf-8;
location / {
index index.php;
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1;
break;
}
}
location ~ .+.php($|/) {
set $script $uri;
set $path_info "/";
if ($uri ~ "^(.+.php)(/.+)") {
set $script $1;
set $path_info $2;
}
include fcgi.conf;
root D:/Apache2.2/htdocs/myblog;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php?IF_REWRITE=1;
fastcgi_param PATH_INFO $path_info;
fastcgi_param SCRIPT_FILENAME $document_root/$script;
fastcgi_param SCRIPT_NAME $script;
}
location ~* .(jpg|gif|png|js|css)$ {
root D:/Apache2.2/htdocs/myblog;
if (-f $request_filename) {
expires max;
break;
}
}
}
}
include mime.types:少了這行,nginx 會把所有檔案都當成 default_type(application/octet-stream)送出,瀏覽器就不肯把它當 CSS 或 JS 執行。這是多數「資源載不進來」問題的真正根源。.(jpg|gif|png|js|css)$ 先被匹配到,才不會被 rewrite 導去 index.php。expires max:為靜態資源加上長期快取標頭,能明顯降低後續載入時間。!-e $request_filename:檔案實際存在時直接放行,只有找不到才交給 PHP 處理,這是典型的單入口路由寫法。另外提醒:範例中的 root 路徑用了 Windows 風格,實際部署時記得改成對應環境的絕對路徑。改完設定後別忘了 nginx -t 檢查語法,再 nginx -s reload 重新載入。