大网数据广告活动
服务器运维问答

Nginx redirect specific path to a subdomain outside of Wordpress

· 52CE 我爱测

I have a main website using Wordpress powered by Nginx (using HTTPS https://example.com ) and I need to redirect a specific path to another server, responding to the subdomain http://files.example.com (no SSL). Whatever I try, re…

问题原文

原帖链接 · Hipjea · CC BY-SA 4.0

I have a main website using Wordpress powered by Nginx (using HTTPS https://example.com) and I need to redirect a specific path to another server, responding to the subdomain http://files.example.com (no SSL).

Whatever I try, rewrite or redirect 301, I land on Wordpress' 404 error page. I think I can't get outside of Wordpress location within my Nginx configuration :

server {
    listen            443 ssl;
    listen            [::]:443;
    server_name       example.com;

    root              /var/www/wordpress;
    index             index.php index.html index.htm;

    access_log        /var/log/nginx/example.access.log;
    error_log         /var/log/nginx/example.error.log;

    location / {
        try_files $uri $uri/ /index.php?$is_args$args =404;
    }

    if (!-e $request_filename){
        rewrite ^/(.*)$ /index.php break;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log    off;
    }

    location ~ \.php$ {
        include       fastcgi.conf;
        fastcgi_pass  php-wp;
    }

    location /files {
        rewrite ^/files(.*)$ http://files.example.com/files$1 redirect;
    }
}

已采纳解答

原帖链接 · Ivan Shatsky · CC BY-SA 4.0

This if block

if (!-e $request_filename){
    rewrite ^/(.*)$ /index.php break;
}

will rewrite any request for any file that is missing at the /var/www/wordpress folder to WordPress index.php. There is no need for this if block at all, remove it. Last argument of try_files directive can be either a new URI or a HTTP error code, but you are trying to use both. Correct your root location block to

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

For redirecting you don't need a separate location block, just use

rewrite ^/files http://files.example.com$request_uri redirect;

for HTTP 302 temporary redirection or

rewrite ^/files http://files.example.com$request_uri permanent;

for HTTP 301 permanent redirection.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-10-05)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。