我在处理类似请求时遇到了问题https://example.com/blog/blog-post被发送到上游,但随后出现 404https://example.com/blog-post/。问题是上游服务器 (Wordpress) 发出了从 /blog-post 到 /blog-post/ 的 301。请注意重定向 URL 末尾的“/”。为了解决此问题,我将以下行添加到我的 Nginx 配置中。
proxy_redirect https://example.com/ https://example.com/blog/;
这解决了最初的问题,但现在当我尝试从请求登录 WordPress 网站时https://example.com/blog/wp-admin/我被重定向到https://example.com/blog/blog/wp-login.php?redirect_to=https%3A%2F%2Fexample.com%2Fblog%2Fwp-admin%2F&reauth=1
我在上游服务器上的 wp-config.php 文件中有以下语句
define('WP_HOME', 'https://example.com/blog');
define('WP_SITEURL', 'https://example.com/blog');
_SERVER['REQUEST_URI'] = str_replace("/wp-admin/", "/blog/wp-admin/", $_SERVER['REQUEST_URI']);
我尝试删除上述 wp-config.php 文件中的最后一行,但问题并未得到解决。同样,当我从 Nginx 配置中删除 proxy_redirect 行时,最初的问题又出现了。
我是 Nginx 新手,据我所知,我尝试使用 proxy_redirect 执行的操作实际上应该默认处理,但只有当它在那里时才能正确处理,但它会弄乱我登录 wordpress 的过程。有什么想法可以纠正吗?比如,我可以让 Nginx 仅在重定向 URI 中没有“blog/”时处理 proxy_redirect 吗?
这是我当前的 Nginx 配置
map $uri $expires {
default off;
~\.(jpg|jpeg|png|gif|ico|css|js)$ 7d;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
root /home/forge/example.com/current/public;
ssl_certificate /etc/nginx/ssl/example.com/454191/server.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/454191/server.key;
ssl_protocols TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/dhparams.pem;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
#add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
index index.html index.htm index.php;
charset utf-8;
location / {
expires $expires;
try_files $uri $uri/ /index.php?$query_string;
}
location ^~ /blog/ {
#rewrite ^/(.*)$ /$1 last;
proxy_pass https://blog.example.com/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect https://example.com/ https://example.com/blog/;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/example.com-error.log error;
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}