简体   繁体   中英

Nginx redirect 301 the entire content of the folder to a subdomain

I'm using Wordpress and Nginx and I created a sub domain to host all the images

I already updated the database to define all the old url, eg; https://exemple.com/wp-content/uploads/2015/06/image_exemple.jpg to https://static.exemple.com/2015/06/image_exemple.jpg which works good, I can now access to the media thought this subdomain

The sub domain point to the same folder as Wordpress have by default for the medias /wp-content/uploads/

Now I'm trying to redirect the entire folder with a permanent redirect to my sub domain

location = /wp-content/uploads/ {
    rewrite ^(.*)$ https://static.exemple.com/$1 permanent;
} 

Its seems to work, when I do curl -I https://static.exemple.com/ to see the header response; it tell me HTTP/1.1 301 Moved Permanently and the same if I do curl -I https://exemple.com/wp-content/uploads

But when I do for exemple curl -I https://exemple.com/wp-content/uploads/2015/06/image.jpg and https://static.exemple.com/2015/06/image.jpg both reponse is HTTP/1.1 200 OK

It seems to works but but it does mean that the redirect 301 works for the entire content of the folder.. For informations the folder uploads/ have many sub folder.

I tried with

location = /wp-content/uploads/ { 
    return 301 https://static/exemple.com/$request_uri;
}

which response the same... Maybe I did something wrong .. Any help would be appreciated

Ok I resolved the issue. I post it for who want to know how I did it.

The solution, simply put this line in your server block, not in some location.

rewrite ^(/wp-content/uploads)(.*)$ https://static.exemple.com$2 permanent;

now test the request with this command

curl -I https://exemple.com/2015/06/logo.jpg 

You should see as answer HTTP/1.1 301 Moved Permanently

and

Location: https://static.exemple.com/2015/06/logo.jpg

Anyways you can do it with wget or another tools !

wget -d URL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM