Nginx redirect specific path to a subdomain outside of Wordpress
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;
}
}
Solution 1:
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.