FeaturesWP CloudPricingEE CLIContactMy Account
Features
Team Access & User Permissions
Install
Resources
Community
CLEAR
Tutorials
Nginx
Nginx config for www to non-www and non-www to www redirection
Topics
On this page
-
- Getting Started
- Git and File-System Layout (non-default setup)
- Version Constraints
- Managing Themes and Plugins (for entire WordPress site)
- Updating Themes and Plugins (for entire WordPress site)
- Adding Composer Support to Your Own Themes and Plugins (for developers)
- Using Composer to Manage Own Theme/Plugin Dependencies (for developers)
-
- Assigning Multiple IP Addresses to Single LAN Card
- Disable IPv6 on Ubuntu 12.04
- dsh – distributed shell
- fdupes – find & replace duplicate files with hardlinks
- GPG Keys Cheatsheet
- Increase "Open Files Limit"
- kill all php, nginx, mysql or any kind of processes
- Passwordless Authentication for SSH
- Screen
- search replace in multiple files useing grep xargs sed
- Setup sftp
- sysctl.conf
- Timezone Sync
- Using Google Public DNS on Ubuntu Server
- Using openssl to match private key, cerificate and CSR
- Configure Postfix to Use Gmail SMTP on Ubuntu
- Logrotate Example for Custom Logs
- PHP 5.5, MySQL, Postfix, Nginx and WordPress on Ubuntu
- Serverdensity
- Upgrade Ubuntu 10.04 to 12.04
- Using find and sed to replace strings in multiple files
- Webmin
-
- .my.cnf – mysql user & password
- Analyse slow-query-log using Anemometer
- Improving MySQL Query Cache
- MySQL Query Profiling
- Reset MySQL root password
- tuning-primer.sh – an alternative for mysqltuner
- Using MariaDB 10
- Install/Upgrade to MySQL 5.6 on Ubuntu 12.04 LTS
- Change WordPress Domain Name
- Character Sets and Collations
- Enable innodb_file_per_table
- Enable Remote Access (Grant)
- Installing Percona Toolkit
- Using tmpfs for temporary folder creation
- YARPP and InnoDB
- Convert MyISAM to InnoDB
- Using tmpfs for mysqldump & mysqlimport
- Convert from INNODB to MYISAM
- Analyse slow-query-log using mysqldumpslow & pt-query-digest
- mysqlcheck with cron to optimize automatically
- Using MySQLTuner to Optimize MySQL configuration
-
-
- Directly connect to PHP-FPM
- Generating core-dump for php5-fpm
- GeoIP
- Having php5 and php7 on same system.
- Install Xdebug and configure it with webgrind
- Installation of PHP Code Review Tools
- memcache
- PHP's Zend Opcache Config & Web Viewer
- Setting Sqlite support with PHP
- Using HHVM with PHP-FPM Fallback
- Using Redis for PHP Sessions on Ubuntu Server
- Installing PhpMyAdmin Quickly
- Moving PHP's session storage to tmpfs
- Install Xdebug and configure it with Netbeans
- Nginx – Enable PHP-FPM Status Page
- PHP-FPM: Socket vs TCP/IP and sysctl tweaking
- APC Cache Optimization & Monitoring Using Web Interface
- Checking if PHP/WordPress can send mails
- Debugging PHP Scripts Using slow_log and more
- Increase file upload size limit in PHP-Nginx
- Increase PHP script execution time with Nginx
-
- Performance Optimization
- Remove Query string of css/js files
- Setup ElasticSearch with ElasticPress
- Using Redis for WordPress Object-Cache
- WooCommerce Window Shopping Caching Technique
- Moving WordPress To New Server (Faster)
- Better wp-cron using linux's crontab
- 404 error- Page not Found!!!
- Debugging WordPress with Nginx
Redirect non-www to WWW
Single domain
All domains
From WWW to non-WWW
Single domain
All domains
Nginx config for www to non-www and non-www to www redirection
There are many ways to force Nginx to use either WWW version or non-WWW version of URLs for your site.
We use following codes all the time.
Redirect non-www to WWW
Single domain
server {
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
All domains
server {
server_name "~^(?!www\.).*" ;
return 301 $scheme://www.$host$request_uri;
}
From WWW to non-WWW
Single domain
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
All domains
server {
server_name "~^www\.(.*)$" ;
return 301 $scheme://$1$request_uri ;
}
In both cases, for other-www, we create a altogether different server { } block. IMHO, this is cleanest and optimised way to handle www to non-www and non-www to www redirection.
There are some WordPress plugins available there which can handle this at PHP-level. But for performance reason, always handle things in Nginx, that can be handled in Nginx alone! 😉
Debugging Nginx Configuration
PREVIOUS
Optimizing Nginx Configuration
NEXT
Comments
-
Mitesh Shah
Instead of hardcodes http we can use $scheme
OLD:
return 301 External link to example.com$request_urihttp://example.com$request_uri;New:
return 301 $scheme://example.com$request_uri; -
Hardy Sam
Is it true that www if not redirected permanently to non-www, will hurt site ranking and Google would see it as duplicate contents?
-
I am not sure about Google but technically serving same page on www and non-www (root) domain should be considered duplicate.
-
-
hello thanks for the guide, im using redirect non to www
the code “for all domain” works for me but the single domain code is not work-
Please send your config for single domain via pastebin. Most likely your
server_namedirective is wrong.
-
-
Dr.Phunk
Can you tell me what’s the difference here between single and all domain.
If I need to strip www from even all the subdirectories then what shall be used ? -
Dr.Phunk
Actually, I am an apache user and very new to nginx so please tell me where to save these codes under which directory and with what file name and file type?
As there is nothing like .htaccess for nginx -
Sameer Joshi
The single domain config will add a redirection only to a specific domain that you have mentioned in the configuration. Hence, the config in the post has example.com domain which you can replace with the specific single domain.
The All domains config will add it to all the domains for which requests are made on the server.
These config will be added to your Nginx configuration file. It will typically be under
/etc/nginx/sites-available/example.comOnce you add the rule test your nginx configuration by
nginx -tIf the test is passed then reload the Nginx process by
service nginx reload -
Mardix
I don’t know if it’s a typo or something, but for me, to redirect WWW to Non-WWW I had to flip your code this way:
server {
server_name “~^www\.(.*)$” ;
return 301 $scheme://$1$request_uri;
}-
Looks like I forgot quotes. Updated article. Thanks.
-
-
Ana
Its not working for me. I tried many options of putting server {
server_name “~^(?!www\.).*” ;
return 301 $scheme://www.$host$request_uri;
}
but nothing works for me.
Here is my sites available file External link to pastebin.comhttp://pastebin.com/aTy9xtca-
I think above 2 lines are losing precedence to
*.bestdocumentariesonline.com
Reference: External link to nginx.orghttp://nginx.org/en/docs/http/server_names.htmlIn that case you can try adding a line like below index line inside
server {..}blockif ( $http_host ~* "www\.(.*)") { rewrite ^ http://$1$request_uri permanent; }Please be careful about first line as I am writing it without tasting.
-
Ana
Thanks Rahul but nothing works for me:(. I added your line and same, also I added this line server {
server_name “~^(?!www\.).*” ;
return 301 $scheme://www.$host$request_uri;
} also in nginx.conf file so also isnt working (basically I try all these lines on different positions and same again. when without www it shows all ok when with www Server not found. Maybe problem in this that my External link to www.mysite.comhttp://www.mysite.com was never reachable? Maybe I should do something to bring this www to live site and then to redirect. ? -
Ana
Thanks Rahul but not success. I added this line and I was trying with different lines different positions and even different files f.e. ngnix.conf (where I should exactly add this line?)
I think that problem can be because my www never was reachable . Maybe I should do something to make it reachable and to point to my site and then to redirect?-
Sorry for delayed reply. At this point, I won’t be able to debug further via comments only.
You need to make sure:
1. For all desired domains, DNS lookup reaches to your server’s IP.
2. Nginx server_name block as wildcard e.g. *.example.com and/or listening by default on that IP. “listening by default” is recommended for domain-mapping.
3. You need to use rules like I posted in previous comment “if server_name starts with www, regex to fetch domain/hostname without www and redirect to it”There are few more ways and tricks but its not possible for me to debug it like this. You can give it a try, or may hire somebody as a last resort.
-
Ana
Thanks Rahul. You idea brought me to solve this issue with redirection.
Only I don’t know if I did it right way (to not have further problems).
What I did: I added 2 CNAME records in my dns:
CNAME * @
CNAME www @
and also your line for this article and all is redirecting now properly.
What o you think is this all correct way as I newer heard for www line before.
Cheers! -
You don’t need CNAME record for WWW. It will be covered by wildcard record in your case.
-
-
-
-
-
Putting it in to nginx.conf inside http { } but it’s not working.
-
What error did you get?
-
-
No error, it just not redirecting from www to non-www. Using nginx as reverse proxy with apache.
-
Why are you using Apache? I think you haven’t followed our setup so I am not sure what problems you are facing.
If you can start afresh, try using easyengine – External link to rtcamp.comhttp://rtcamp.com/easyengine
-
-
Fahad
I am very impress with your all article.
Please guide how do we enable functionality for External link to www.subdomains.domain.comhttp://www.subdomains.domain.com where subdomains list come from database namse is subdomain.php . i tried following which is not working
server { listen 80; server_name www.domain.com *.domain.com; ............**if ($http_host !~ "^(www\.)?domain\.com"){ rewrite !^subdomain\.php$ /subdomain.php break; }**location / { root /usr/share/nginx/html/domain.com/; index index.php; .......-
Sorry, I couldn’t understand your problem properly.
-
Fahad
When client do visit at rahul.mydomain.com
First it will auto redirect at External link to www.rahul.mydomain.comhttp://www.rahul.mydomain.com and check rahul name my db by using php code “subdomains.php”
& get the all profile page
like External link to www.rahul.mydoamin.comhttp://www.rahul.mydoamin.com/index.
like External link to www.rahul.mydoamin.comhttp://www.rahul.mydoamin.com/profile.
like External link to www.rahul.mydoamin.comhttp://www.rahul.mydoamin.com/contect.i tried followings on Nginx
if ($http_host !~ “^(www.)?domain.com”){
rewrite !^subdomain.php$ /subdomain.php break;
}Please Help
-
I assume
rahulfromwww.rahul.mydomain.comwill be passed tosubdomain.phpas an argument.Something like:
subdomain.php?domain=rahulIf that is the case, you need to change regex to something like: (please note first line)
if ($http_host !~ "^(www.)?([^\.]*)\.domain.com"){ try_files /subdomain.php?domain=$2 =404; }I am assuming subdomain.php is present in root.
I think you don’t need rewrite. You just need to tell nginx to use subdomain.php in a particular case (with may be some arguments)
-
-
-
-
Chirag
I would like to redirect one page on my site to homepage. Without affecting sub-pages..
like redirecting site.com/abc to site.com without getting redirect loop in site.com/abc/xyz
How can that be done? I read about modifying conf file in /etc/nginx… but in my case there is no nginx directory within etc.
-
In site.com server block, add
rewrite ^/abc$ http://site.com/abc/xyz last;^and$will make sure no redirect loop starts.
-
Features
- Server Setup & Management
- Site Creation & Management
- Create WP Cloud Sites
- Speed & Caching
- Firewall Protection
- Backups & Recovery
- Logs & Monitoring
- Deployments & Developer Tools
- Team Access & User Permissions
Useful Links
Product
Other Products
Subscribe for curated product updates, tips, and announcements.
"*" indicates required fields
URL
This field is for validation purposes and should be left unchanged.
Email*
SIGN ME UP
Δ
© rtCamp, since 2009. All rights reserved.