How to redirect single url in nginx?

2019-01-12 16:30发布

I'm in the process of reorganizing url structure. I need to setup redirect rules for specific urls - I'm using NGINX.

Basically Something like this:

http://example.com/issue1 --> http://example.com/shop/issues/custom_issue_name1
http://example.com/issue2 --> http://example.com/shop/issues/custom_issue_name2
http://example.com/issue3 --> http://example.com/shop/issues/custom_issue_name3

Thanks!

标签: nginx rewrite
3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-12 16:57
location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}
查看更多
成全新的幸福
3楼-- · 2019-01-12 17:07

If you need to duplicate more than a few redirects, you might consider using a map:

map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}
查看更多
狗以群分
4楼-- · 2019-01-12 17:08

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...
查看更多
登录 后发表回答