Home  >  Q&A  >  body text

How to write nginx subdirectory 301 redirect

I recently encountered such a problem about the website.
The PC address page is similar to www.abc.com/pc/123/index.html
The corresponding M-side address is m.abc.com/sj/123/index.html
123 This directory is not fixed There are other names, pc and sj are fixed, so there are other such correspondences, such as:
PC www.abc.com/pc/222/index.html
M m.abc.com /sj/222/index.html

You need to make a judgment and jump in nginx here. My original writing method is:

location /pc/ {
    if ($http_user_agent ~* "((Android)|(blackberry)|(googlebot-mobile)|(iemobile)|(ipad)|(iphone)|(opera mobile)|(palmos)|(webos)|(UCBrowser)|(wap)|(Opera Mobi))"){
                    return 301 http://m.abc.com/sj$request_uri;
}

Obviously the above writing method will become a jump corresponding to this:
PC www.abc.com/pc/222/index.html
M m.abc.com/sj/pc/222/ index.html
This is not what I want. How to remove the pc directory from $request_uri?
Please ask God. How to rewrite?

ringa_leeringa_lee2691 days ago965

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-06-06 09:56:36

    location ~ /pc/(.*) {
        if ($http_user_agent ~* "((Android)|(blackberry)|(googlebot-mobile)|(iemobile)|(ipad)|(iphone)|(opera mobile)|(palmos)|(webos)|(UCBrowser)|(wap)|(Opera Mobi))"){
                        return 301 http://m.abc.com/sj/;
    }
    不知道这样行不行

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-06 09:56:36

    location ~ ^/pc/(.*) {
        if ($http_user_agent ~* "((Android)|(blackberry)|(googlebot-mobile)|(iemobile)|(ipad)|(iphone)|(opera mobile)|(palmos)|(webos)|(UCBrowser)|(wap)|(Opera Mobi))") {
            return 301 http://m.abc.com/sj/$1;
        }
    }

    reply
    0
  • Cancelreply