Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to get a domain name when Nginx redirects

Shulou Source: shulou.com Published: 2022-06-01 21:25:53 09月20日 Update

How do I get a domain name when Nginx redirects? I believe that many inexperienced people are at a loss about this, so this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

The HTTP request is redirected to the HTTPS request with the same name. The configuration is as follows:

Http {server {listen 80; server_name sub1.example.com sub2.example.com; return 301 https://$server_name$request_uri;} server {listen 443 ssl spdy; server_name sub1.example.com sub2.example.com; #...}}

Because 301 is a permanent redirect, the cache of some browsers will remember the redirection, and the next time you visit the original address, the request will be sent directly to the new address, so this problem may not be reproduced in the browser (including Chrome's Incognito Window). The only way to reproduce it completely each time is curl.

$curl-I http://sub2.example.com/HTTP/1.1 301 Moved PermanentlyServer: nginx/1.9.3 (Ubuntu) Date: Tue, 23 Feb 2016 06:06:30 GMTContent-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: https://sub1.example.com/

Check it out and find that the problem lies with the $server_name variable. This variable always returns the first name in server_name. You should actually use the $host variable here. The modified configuration is as follows:

Http {server {listen 80; server_name sub1.example.com sub2.example.com; return 301 https://$host$request_uri;}}

The $host variable acquires the domain name according to the following priority:

Domain name information in Request-Line. Request-Line contains method, uri and HTTP versions.

"Host" in the request header information.

Matching server_name configuration in Nginx.

After reading the above, have you mastered how to get the domain name when Nginx redirects? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Domain name variable problem configuration information content address method more browser browsing helpless for this priority reason only name for this come on skill Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Redmi MariaDB Linux Docker