Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx return under location

I am currently facing a small problem using nginx to redirect to another host. I want to for example redirect https://service.company.com/new/test.html to https://new-service.company.com/test.html .

For now I have following configuration, which redirects me to https://new-service.company.com/new/test.html .

server {
        # SSL
        ssl_certificate /etc/nginx/cert/chained_star_company.com.crt;
        ssl_certificate_key /etc/nginx/cert/star_company.com.key;

        listen 443;
        server_name service.company.com;

        location /new/$1 {
        return 301 $scheme://service-new.company.com/$1;
    }

}

I also tried following with the same result:

return 301 $scheme://service-new.company.com/$request_uri
like image 210
jcrosel Avatar asked Jan 24 '17 13:01

jcrosel


People also ask

What is return 301 in nginx?

Temporary and Permanent Nginx Redirect Explained To map this change, the redirects response code 301 is used for designating the permanent movement of a page. These kinds of redirects are helpful when the user wants to change the domain name and no longer wants a browser to access it.

How does nginx match location?

To find a location match for an URI, NGINX first scans the locations that is defined using the prefix strings (without regular expression). Thereafter, the location with regular expressions are checked in order of their declaration in the configuration file.

What is return in nginx?

NGINX Return directive in Server context As soon as NGINX receives an URL with www.olddomain.com, it stops processing the page and sends a 301 response code along with rewritten URL to the client. The two variables used in the above return directive are $scheme and $request_uri .

What is $URI in nginx?

It is exactly the $uri/ part that makes nginx assuming an URI can be a directory name and looking for an index file presence inside it.


1 Answers

You want to rewrite the URI and redirect. You can achieve it using location and return directives, but a rewrite directive would be the simplest approach:

rewrite ^/new(.*)$ https://new-service.company.com$1 permanent;

See this document for more.

BTW, the problem with your location block solution, was the regular expression capture, wasn't. Use:

location ~ ^/new(.*)$ {
    return 301 https://new-service.company.com$1$is_args$args;
}

See this document for more.

like image 57
Richard Smith Avatar answered Nov 15 '22 07:11

Richard Smith