Nginx

Nginx 伺服器配置 - 重寫問題

  • October 19, 2011

我有以下伺服器配置:

server {
   listen       80;
   server_name  mysite.proj;

   location / {
       root /path/to/mysite.proj/www;
       index index.php index.html index.htm;
   }

   access_log /path/to/mysite.proj/data/logs/access.log;
   error_log  /path/to/mysite.proj/data/logs/error.log;

   if (!-e $request_filename) {
       rewrite ^(.+)$ /index.php last;
   }

   location ~ \.php$ {
       root           /path/to/mysite.proj/www;
       fastcgi_pass   127.0.0.1:8081;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  /path/to/mysite.proj/www$fastcgi_script_name;
       include        fastcgi_params;
   }
}

server {
   listen 80;
   server_name www.mysite.proj;
   rewrite ^/(.*) http://mysite.proj/$1 permanent;
}

它工作正常,每個 url 都被重寫為 index.php。但同時每個樣式表 url、每個 javascript url、每個圖像 url 也會被重寫。如何編寫重寫規則以不重寫 css、js、圖像文件的 url?

您沒有在伺服器上下文中設置根,這是 if 所在的位置,因此它使用預設的 <install prefix>/html。您應該將根移動到伺服器上下文並切換 if 為 try_files。此外,沒有理由在 no-www 重定向中擷取請求,因為原始請求已經儲存在 $request_uri 中。

server {
   listen 80;
   server_name www.mysite.proj;
   # Permanent redirect to no-www
   return 301 http://mysite.proj$request_uri;
}

server {
   listen 80;
   server_name mysite.proj;

   root /path/to/mysite.proj/www;
   index index.php index.html index.htm;

   access_log /path/to/mysite.proj/data/logs/access.log;
   error_log  /path/to/mysite.proj/data/logs/error.log;

   location / {
       # try_files does not preserve query string by default like rewrite
       try_files $uri $uri/ /index.php$is_args$args;
   }

   location ~ \.php$ {
       # If the requested file doesn't exist, and /index.php doesn't, return a 404
       try_files $uri /index.php =404;

       include        fastcgi_params;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       fastcgi_pass   127.0.0.1:8081;
   }
}

引用自:https://serverfault.com/questions/323009