我在我的网站的根文件夹中有一个PHP应用程序(Wordpress),所有对网站的请求都很愉快地运行。
不过,我有一个子文件夹_links,我想用它来执行另一个不同的PHP脚本。
例如,如果用户访问site.com/_links/221312,则来自/ _links的index.php脚本将接pipe。
我以前使用一个.htaccess文件来实现这一点,但既然搬到nginx我不能让它工作。
这是旧的.htaccess文件。
RewriteEngine On RewriteRule ^([0-9]+)/?$ index.php?linkid=$1 [NC,L]
显然,我将URL的最后一位作为parameter passing给脚本。
这是我的nginxconfiguration。 请求例如site.com/_links/23423被if (!-e $request_filename) /index.php?q=/_links/23423 ,并被重写为/index.php?q=/_links/23423而不是被位置块拾取。
server { listen 127.0.0.1:8080; server_name site.com www.site.com m.site.com; root /var/www/site; location ^~ /_links/ { add_header location 1; root /var/www/site/_links; rewrite "^([0-9]+)/?$" /index.php?linkid=$1 break; location ~ \.php$ { try_files $uri =404; 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 index.php index.html; if (!-e $request_filename) { rewrite ^(.+)$ /index.php?q=$1 last; } location / { try_files $uri $uri/ =404; } # pass the PHP scripts to FastCGI server listening on the php-fpm socket location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } access_log /var/log/nginx/site.com.access.log; error_log /var/log/nginx/site.com.error.log notice; }
我很困惑。 这里发生了什么?
也许是因为位置块上的前缀匹配( ^~ ), nginx正在跳过正则expression式检查 :
如果最长匹配的前缀位置具有“^〜”修饰符,则不检查正则expression式
尝试删除前缀检查即:
location /_links/ { Regex here }
另外删除 location /_links/ block内的根声明你不需要它,查看nginx的陷阱了解更多信息,基本上服务器是使用root declaration ,然后位置匹配$root/$location
同样如上面的build议看看try_files指令而不是if(condition){match}
即,而不是:
if (!-f $request_filename) { rewrite ^/(.*)$ /index.php?q=$1 last; }
更好的解决scheme是:
try_files $uri $uri/ /index.php?q=$uri;
这也是在nginx陷阱wiki页面中提到的。
尽可能避免嵌套位置。 重写location ^~ /_links/到location ^~ /_links/ location ^~ /_links/.*\.php ,我希望这是你所需要的。 如果你只使用一个位置来存放* .php文件,这可能会更好,可能会把你的一些重写文件移到那里。