Score:0

Nginx redirect specific path to a subdomain outside of Wordpress

cn flag

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;
    }
}
Score:1
gr flag

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.

Hipjea avatar
cn flag
Thank you for this detailed answer ! That's working perflectly and it's more clear in my mind.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.