http://example.com/oldpage?server {
listen 80;
server_name example.com;
location / {
if ($request_uri = "/oldpage") {
return 301 /newpage;
}
root /var/www/html;
}
}The if condition checks if the requested URI is exactly /oldpage. If true, it sends a permanent redirect (301) to /newpage. Otherwise, it serves files from the root directory.
location / {
if ($request_uri ~* "/oldpage") {
return 301 /oldpage;
}
}
Why does this cause a redirect loop when visiting /oldpage?The config redirects /oldpage to /oldpage again, causing the browser to keep requesting the same URL and nginx to keep redirecting it, creating a loop.
/submit to /process permanently. Which nginx config snippet achieves this?Option B uses an exact match location for /submit and inside it checks if the method is POST, then redirects. This ensures only POST requests to /submit are redirected.
if directive inside nginx location blocks for conditional redirects?nginx documentation warns that 'if' inside location blocks can cause unexpected results and should be used carefully, especially for complex logic. It's better to use other directives or map blocks when possible.
First backup current configs to avoid loss. Then add the new 'if' redirect. Test syntax to catch errors. Finally reload nginx to apply changes.