1

I have a react app running on a fresh Ubuntu 24 LEMP server. The previous version of this server hosted a blog that lived at www.example.com/blog/. On this new version of the server, I've moved the blog and it's contents to a subdomain, data.example.com/blog/. So www.example.com/blog/.... does not exist (there is no blog folder there at all).

I now need to redirect all the prior uploaded files from the old, no longer in existence directories, to their new locations on the subdomain. The old uploads lived in directories such as /blog/wp-content/uploads/2016/05/whatever.jpg - meaning the year (2016), the month (05) and the file (whatever.jpg) could vary, but everything else was static.

I've tried a million things to get this redirect to work, but no luck. Can anyone point me in the right direction? Here are some examples of what I've tried and failed with so far:

/etc/nginx/sites-available/example.com.conf:

server {
  location / {
    # these result in a white page that reads 'file not found'
    # the url in the address bar does not change at all, no redirect takes place.
    # I do NOT have them both active at the same time, of course.
    rewrite ^(/blog/wp-content/uploads)(.*)$   https://data.example.com.com/blog/wp-content/uploads/$2 permanent;
    rewrite ^(/blog/wp-content/uploads/(.*)/(.*))(.*)$   https://data.example.com.com/blog/wp-content/uploads/$2 permanent;
  }

location /blog/wp-content/uploads/ { # these ones load the shell of the react app (header/footer etc) with no page content (I haven't yet configured a custom 404 in the react app) # no redirect takes place rewrite ^(/blog/wp-content/uploads/)/(.)$ https://data.example.com.com/blog/wp-content/uploads/$2 permanent; rewrite ^(/blog/wp-content/uploads/(.)/(.))/(.)$ https://data.example.com.com/blog/wp-content/uploads/$2 permanent; } }

EDIT: this is not the same as the question In Nginx, how can I rewrite all http requests to https while maintaining sub-domain?. That question is asking how to redirect all requests while maintaining subdomain. I'm asking how to redirect certain requests while changing the subdomain. I also believe the fact that my path does not exist and has partial wildcards complicates the issue. It looks to me like the answers there would redirect my entire site. That's not what I'm trying to do.

1 Answers1

1

If I understood your question correctly, you want to redirect all old domain URLs to new domain. If that is the case, then this should work:

server {
    server_name example.com;
    ...
    location /blog {
        return 301 https://data.example.com$request_uri;
    }
}

Here nginx will issue a 301 redirect for all requests whose path part begins with blog. It will redirect them to the new domain with the original path.

Tero Kilkanen
  • 38,887