Nginx - rewrite or return for redirection?

Solution 1:

Your option 1:

return 301 $scheme://$host$request_uri;

Is exactly what you want.

Not sure why the rewrite ^ http://$host$request_uri? permanent; line would result in a 302 instead of 301. That's the proper syntax to force it to return a 301.

Solution 2:

Technically, you can use both options. They can work.

According to the NGINX documentation, use return if you can. It is simpler and faster because NGINX stops processing the request (and doesn't have to process a regex). More than that, you can specify a code in the 3xx series:

return (301 | 302 | 303 | 307) url;

If you have a scenario where you need to validate the URL with a regex or need to capture elements in the original URL (that are obviously not in a corresponding NGINX variable), then you should use rewrite. You must know that rewrite returns only code 301 or 302.

rewrite regex URL [flag];

You can read more about return and rewrite on the NGINX website.

Tags:

Linux

Nginx