{"id":12119,"date":"2022-03-21T14:54:33","date_gmt":"2022-03-21T18:54:33","guid":{"rendered":"http:\/\/local.brightwhiz\/?post_type=snippets&p=12119"},"modified":"2022-03-21T14:54:35","modified_gmt":"2022-03-21T18:54:35","slug":"nginx-redirect-www-to-non-www-and-non-www-to-www","status":"publish","type":"snippets","link":"http:\/\/local.brightwhiz\/snippets\/nginx-redirect-www-to-non-www-and-non-www-to-www\/","title":{"rendered":"Nginx Redirect www to non-www and non-www to www"},"content":{"rendered":"\n
Code for Nginx redirect www to non-www with a non-hard coded domain name.<\/p>\n\n\n\n
server {\n ...\n # Redirect www to non-www\n if ( $host ~ ^www\\.(?<domain>.+) ) {\n rewrite ^\/(.*)$ $scheme:\/\/$domain\/$1;\n }\n}<\/code><\/pre>\n\n\n\nUsing hardcoded server_name<\/code>.<\/p>\n\n\n\nserver {\n server_name www.example.com;\n return 301 $scheme:\/\/example.com$request_uri;\n}\n\nserver {\n server_name example.com;\n # more configuration options here\n}<\/code><\/pre>\n\n\n\nExample code snippet for non-www to www.<\/p>\n\n\n\n
server { \n if ($host !~ ^www\\.) {\n rewrite ^ https:\/\/www.$host$request_uri permanent;\n } \n}<\/code><\/pre>\n\n\n\nAnother way: Hardcoded Nginx non-www to www for a single domain.<\/p>\n\n\n\n
server { \n ...\n server_name example.com; \n return 301 https:\/\/www.example.com$request_uri;\n}<\/code><\/pre>\n\n\n\nFor All Domains:<\/p>\n\n\n\n
server {\n server_name "~^(?!www\\.).*" ;\n return 301 $scheme:\/\/www.$host$request_uri;\n}<\/code><\/pre>\n","protected":false},"comment_status":"open","ping_status":"closed","template":"","meta":[],"categories":[953,23,15,16,18],"tags":[350,400,424,433,449,526,531,591,635,638],"yoast_head":"\nNginx Redirect www to non-www and non-www to www<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n