Nginx

Nginx 重寫問題

  • July 29, 2013

我想要我的一個虛擬伺服器的特定配置,但我在向 Nginx 解釋時遇到問題:)

它很簡單。如果 URI 看起來像

example.com/whatever_1/whatever_2/.../whatever_n

我想將其重寫為

example.com/index.php?request=whatever_1/whatever_2/.../whatever_n

第二個是如果URI以/administration/like開頭

example.com/administration/whatever_1/.../whatever_n

我希望它被重寫為

example.com/administration/index.php?request=whatever_1/.../whatever_n

我正在修補周圍並嘗試過:

server
{
#   listen 80;
   server_name example.com;
   index index.html index.php;
   root /srv/example/;

   location ~ /administration/(.*)$
   {
       if (!-e $request_filename)
       {
           rewrite ^/(.*)$ /administration/index.php?request=$1 last;
       }
       break; #tried with and without it
   }

   location / #tried with and without this location block
   {
       if (!-e $request_filename)
       {
           #rewrite ^/(.*)$ /index.php?/$1 last;
           rewrite ^/(.*)$ /index.php?request=$1 last;
       }
   }

   location ~ \.php$ #boilerplate
       {
               # Filter out arbitrary code execution
               fastcgi_index index.php;
               include fastcgi_params;
               fastcgi_pass  unix:/var/run/php5-fpm.sock;
       }
}

但這不起作用。我對 Nginx 很陌生,所以任何幫助都將不勝感激。

謝謝,簡。

這是 nginx,而不是 apache。您應該盡可能避免重寫(而且通常是可能的)。

改為使用try_files。例如:

location /administration/ {
   try_files $uri $uri/ /administration/index.php?request=$request_uri;
}

location / {
   try_files $uri $uri/ /index.php?request=$request_uri;
}

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