【发布时间】:2021-01-30 15:08:39
【问题描述】:
我有一些类似的网站
http://localhost/myweb1
http://localhost/myweb2 等等。
我需要将下面对 myweb1 的示例请求重定向到 http://localhost/myweb1/index.php 中的 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 的配置
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语句放错了位置。与其在每个location块中使用相同的root语句,不如在server块中使用一个root语句,它允许每个location块继承它。
标签: php nginx url-rewriting config