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
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With