这与几年前我问过的一个老问题有关 ,对此我从来没有得到正确的答案。 我只是build立一个新的服务器(Ubuntu 16.04,Nginx 1.10,PHP 7),并回到这个。
我有一个Question2Answer实例运行在一个子文件夹中,其他PHP代码从根目录运行。 对于根的东西,我有这在我的服务器块:
location / { try_files $uri $uri/ /index.php?$request_uri; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; }
对Q2A来说,我在旧服务器上所拥有的是:
location /qa/ { if (!-e $request_filename) { rewrite ^/qa/(.*)$ /qa/index.php?qa-rewrite=$1 last; } }
这是行得通的,但我不认为这是应该如何做(如果是邪恶等)。 我确定只能使用try_files 。 我试过这个:
location /qa/ { try_files $uri $uri/ /qa/index.php?qa-rewrite=$uri&$args; }
但是它不起作用,因为/qa/在qa-rewrite传递。 它应该只是通过path后的一切。 有没有办法从$urivariables中删除/qa/ ?
我也试过这个:
location ~ ^/qa/(.*) { try_files $uri $uri/ /qa/index.php?qa-rewrite=$1; }
但是,这反而开始下载index.php的PHP代码! 我怎样才能把它传递给PHP引擎?
如果是邪恶的,但正如文件所述 ,可以rewrite ... last陈述。
但是,另一种方法(仍然只提取$uri )是在try_files语句的末尾使用一个命名的位置:
location /qa/ { try_files $uri $uri/ @qa; } location @qa { rewrite ^/qa/(.*)$ /qa/index.php?qa-rewrite=$1 last; }
正则expression式的方法也是有效的。 但是,正则expression式位置的评估方式与前缀位置不同 。 您需要将location ~ \.php$块放在 location ~ ^/qa/(.*)块的location ~ ^/qa/(.*) ,以便以.php结尾的URI在正确的位置处理。