You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx HTTP跳转异常:访问HTTP域名跳转到localhost而非指定域名

Fixing Nginx HTTP to HTTPS Redirect to localhost Issue

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:

  1. Conflicting default_server settings: Your HTTP server block uses listen 80 default;, but if there's another config file in /etc/nginx/conf.d/ (like the default default.conf) that also claims default_server on 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 to localhost.
  2. $server_name isn't always reliable: The $server_name variable pulls directly from your Nginx config's server_name value, 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 $host variable 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 like default.conf. If you find one with listen 80 default_server;, either delete the file or edit it to remove the default_server flag (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:20:44