Quite often I encounter such redirects in Nginx configuration:
server {
listen 80;
server_name www.example.org;
rewrite ^(.*)$ $scheme://example.org$uri;
}
I see three problems with this approach. Let’s fix them one by one.
First, use of regular expressions for such a simple case is unwarranted. return seems good enough:
server {
listen 80;
server_name www.example.org;
return 302 $scheme://example.org$uri;
}
Second, in such cases we usually want permanent redirect. The rewrite use as in first snippet (rewrite ^(.*)$ $scheme://example.org$uri;) generates 302 Found. Let’s generate 301 Moved Permanently:
server {
listen 80;
server_name www.example.org;
return 301 $scheme://example.org$uri;
}
Finally, $uri is not necessarily original URI. For redirects it may be better to use “full original request URI (with arguments)”—$request_uri:
server {
listen 80;
server_name www.example.org;
return 301 $scheme://example.org$request_uri;
}
For example, my static blog engine (that powers this site) generates configuration with permanent redirect and $request_uri as I recommend here.
This blog is about things I encounter while doing web and non-web software development.