Nginx如何将仅对某个目录路径的请求重定向到该目录中的index.php?
我有一些网站像 http://localhost/myweb1 http://localhost/myweb2 等等 我需要将下面myweb1的示例请求重定向到中的index.phphttp://localhost/myweb1/index.php 而myweb2不应受到影响 http://localhost/myweb1/user http://localhost/myweb1/user/account http://localhost/myweb1/product 等等应该重定向到myweb1/index.php 下面是我在/etc/nginx/conf.d/default.conf的配置Nginx如何将仅对某个目录路径的请求重定向到该目录中的index.php?,php,nginx,url-rewriting,config,Php,Nginx,Url Rewriting,Config,我有一些网站像 http://localhost/myweb1 http://localhost/myweb2 等等 我需要将下面myweb1的示例请求重定向到中的index.phphttp://localhost/myweb1/index.php 而myweb2不应受到影响 http://localhost/myweb1/user http://localhost/myweb1/user/account http://localhost/myweb1/product 等等应该重定向到myweb
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
location ~ \.php$ {
root /usr/share/nginx/html;
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
答复由
您可以添加
location/myweb1{try_files$uri$uri//myweb1/index.php;}
@RichardSmith谢谢,我添加了它,它几乎可以工作,除了直接文件名为myweb1.css或myweb1.js的请求也被重定向到index.php,这导致网页无法加载这些资源。我如何使没有文件扩展名的请求被重定向?你是说这些文件不存在,所以你希望Nginx用404来响应吗?使用:location~ \(css | js)${}
(空括号是您所需要的全部)@RichardSmith这些文件存在,应该可以访问,但现在已重定向到index.php。例如,localhost/myweb1/user将加载需要在localhost/myweb1/myweb1.css加载css文件的网页,但现在对myweb1.css的访问已重定向到index.php,这是不正确的。所以我需要的是像myweb1/user这样的请求应该重定向到index.php,但是像myweb1/myweb1.css或myweb1/myweb1.js等请求不应该重定向到index.php。简言之,只有不带任何文件扩展名的请求才应该重定向到index.php。您的root
语句位于错误的位置。不要在每个位置
块中都有相同的root
语句,而应该在服务器
块中使用一个root
语句,它允许每个位置
块继承它。
root /usr/share/nginx/html;
location /myweb1 { try_files $uri $uri/ /myweb1/index.php; }