Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I want to redirect the site ALWAYS to www.site.com. However, I am not sure as to how to get the WWW to always show up in front should say someone type in the domain without the www.

EDIT:

server {
        listen  80;
        server_name  site.com;
        rewrite ^(.*) https://www.site.com$1 permanent;
}

server {
    listen       80;
    server_name  www.site.com;
    #rewrite ^(.*) https://www.site.com$1 permanent;
    root /home/site/public_html;

        listen       443 ssl;

If I type in site.com it goes to https://www.site.com = SUCCESS

If I type in site.com/index.php it goes to http://www.site.com = NO SSL

Ideas?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You're doing it the hard way. Here's the easy way.

server {
    listen 80;
    server_name  example.com;
    rewrite ^(.*) http://www.example.com$1 permanent;
}

server {
    listen 80;
    server_name  www.example.com;
    #The rest of your configuration goes here#
}
share|improve this answer

Better use return instead of rewrite, because it's faster

server {
    listen 80;
    server_name     example.com;
    return          301 http://www.example.com$request_uri;

server {
    listen 80;
    server_name     www.example.com;
    [...]

This way, we also send the client a proper status code, so that he asks the right domain in the next request.

share|improve this answer
1  
Gave you an upvote, but thought I'd note that rewrite permanent sends a 301, too. –  ceejayoz May 11 '13 at 23:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.