简体   繁体   English

Nginx将文件夹的全部内容重定向301到子域

[英]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 我正在使用Wordpress和Nginx,并创建了一个子域来托管所有图像

I already updated the database to define all the old url, eg; 我已经更新了数据库以定义所有旧的url,例如; 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 https://exemple.com/wp-content/uploads/2015/06/image_exemple.jpghttps://static.exemple.com/2015/06/image_exemple.jpg效果很好,我现在可以访问媒体了以为这个子域

The sub domain point to the same folder as Wordpress have by default for the medias /wp-content/uploads/ 子域指向与Wordpress相同的默认文件夹,用于/ 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; 当我curl -I https://static.exemple.com/时,它似乎正常工作curl -I https://static.exemple.com/查看标题响应; it tell me HTTP/1.1 301 Moved Permanently and the same if I do curl -I https://exemple.com/wp-content/uploads 它告诉我HTTP / 1.1 301永久移动 ,如果我curl -I https://exemple.com/wp-content/uploads则保持不变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 但是当我做示例卷曲时-我https://exemple.com/wp-content/uploads/2015/06/image.jpghttps://static.exemple.com/2015/06/image.jpg都响应是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. 它似乎有效,但是它确实意味着重定向301适用于文件夹的整个内容。有关此信息,文件夹上载/具有许多子文件夹。

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 您应该看到答案HTTP / 1.1 301永久移动

and

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

Anyways you can do it with wget or another tools ! 无论如何,您都可以使用wget或其他工具来完成!

wget -d URL wget -d URL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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