[Nginx] How to Configure Redirects from www URLs to Non-www URLs

Tadashi Shigeoka ·  Wed, September 26, 2012

I’ll introduce how to configure Nginx to redirect URLs with www to URLs without www.

Nginx

The following configuration redirects access from www.codenote.net to codenote.net.

server {
    listen 80;
    server_name www.codenote.net;
    rewrite ^ http://codenote.net$request_uri? permanent;
}

Since www URLs will always redirect to non-www URLs in the future, I set the last redirect flag to permanent.

There are various types of redirect flags, so please change the settings according to your situation.

The HTTP status code changes depending on what you specify for the last redirect flag.

・last The rewrite is complete, and matching URI or location processing continues.

・break The rewrite is complete.

・redirect Used for temporary redirects. Returns HTTP status code 302 and executes the redirect.

・permanent Used for permanent redirects. Returns HTTP status code 301 and executes the redirect.

Source: apache のかわりにnginxを使ってみる(4) nginx でリダイレクト ( rewrite ) するには | レンタルサーバー・自宅サーバー設定・構築のヒント

That’s all.

Reference Information

That’s all from the Gemba.