Nginx HTTP跳转异常:访问HTTP域名跳转到localhost而非指定域名
Hey there, let's break down why your redirect is misbehaving and how to fix it quickly.
What's Causing the Problem?
From your config, I spot two likely culprits:
- Conflicting
default_serversettings: Your HTTP server block useslisten 80 default;, but if there's another config file in/etc/nginx/conf.d/(like the defaultdefault.conf) that also claimsdefault_serveron port 80, Nginx might be routing your requests to that unconfigured block instead of your custom redirect rule. That would explain why it's falling back tolocalhost. $server_nameisn't always reliable: The$server_namevariable pulls directly from your Nginx config'sserver_namevalue, but if for some reason the request's Host header doesn't match exactly (or Nginx picks the wrong server block), it won't return the domain you expect. The$hostvariable is better here because it grabs the Host header directly from the incoming request.
Step-by-Step Fixes
1. Resolve default_server Conflicts & Use $host
First, check if there's a conflicting default config:
- Navigate to
/etc/nginx/conf.d/and look for files likedefault.conf. If you find one withlisten 80 default_server;, either delete the file or edit it to remove thedefault_serverflag (so it doesn't compete with your custom block).
Then update your HTTP redirect server block to use $host instead of $server_name, and make sure it listens on both IPv4 and IPv6:
server { listen 80; listen [::]:80; server_name www.example.com; return 301 https://$host$request_uri; }
2. (Alternative) Mark Your Block as the Definitive Default Server
If you want to keep other config files around, explicitly set your redirect block as the default_server for port 80 (only one default_server can exist per port):
server { listen 80 default_server; listen [::]:80 default_server; server_name www.example.com; return 301 https://$host$request_uri; }
Verify & Apply Changes
Before restarting Nginx, always check your config for syntax errors:
nginx -t
If you see "test is successful", restart Nginx to apply the fix:
systemctl restart nginx
This should make sure all HTTP requests to www.example.com get redirected to the correct HTTPS URL instead of localhost.
内容的提问来源于stack exchange,提问作者VictorGalisson

