Nginx Rewrite规则不生效求助:短域名转FQDN配置排查
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
serverblock useslisten 80 default_server, it will take priority. Adddefault_serverto 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'sHostheader matchesfooorfoo.bar.com. - Quick test: Temporarily replace your rewrite rule with
return 200 "Block Test";and restart Nginx. If you see this message when accessinghttp://fooorhttp://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

