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

Nginx Rewrite规则不生效求助:短域名转FQDN配置排查

Troubleshooting Your Nginx Rewrite Rule (nginx/1.13.4)

Let's break down why your rewrite rule isn't taking effect and fix it with actionable steps:

1. First, Confirm the Request Is Hitting the Correct server Block

Nginx matches requests to server blocks based on the Host header and listen directive. If your request is routed to a different block (like a default server), your rewrite will never run.

  • Check for default server conflicts: If another server block uses listen 80 default_server, it will take priority. Add default_server to your listen directive to ensure this block catches matching requests:
    server {
        listen 80 default_server;
        server_name foo foo.bar.com;
        # ... rest of your config
    }
    
  • Verify with logs: Check your Nginx access log (typically /var/log/nginx/access.log) to confirm the incoming request's Host header matches foo or foo.bar.com.
  • Quick test: Temporarily replace your rewrite rule with return 200 "Block Test"; and restart Nginx. If you see this message when accessing http://foo or http://foo.bar.com, the block is being hit.

2. Use return Instead of rewrite for Redirects

return is more efficient and reliable for permanent redirects than rewrite, and it can preserve the original request URI if needed:

server {
    listen 80 default_server;
    server_name foo foo.bar.com;
    rewrite_log on;
    # Redirect to HTTPS while keeping the original request path
    return 301 https://foo.bar.com$request_uri;
    # If you want to redirect *only* to the root, use:
    # return 301 https://foo.bar.com/;
    include includes/web-site;
    include includes/files-site;
}

3. Check for Conflicts in Included Files

While your rewrite runs before the include statements, it's worth verifying that the included files don't have directives that could interfere. Open includes/web-site and includes/files-site to ensure there are no rewrite or return lines that might override your redirect.

4. Fix SSL Block Syntax Errors

Your config snippet cuts off at ssl_certifica...—syntax errors in the SSL block (like a missing ssl_certificate_key line) will prevent Nginx from reloading your new config. Validate your full config with:

nginx -t

Fix any errors (e.g., add ssl_certificate_key foobar.key; to match your certificate file) before restarting Nginx.

5. Check the Rewrite Log

Since you enabled rewrite_log on;, look for lines starting with rewritten request: in your error log (usually /var/log/nginx/error.log). If you don't see these lines, the request isn't hitting your server block. If you do see them, your browser might be caching an old response—test with curl -v http://foo to view the raw redirect.

内容的提问来源于stack exchange,提问作者tyon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:16:35