Mobile app version of vmapp.org
Login or Join
Mendez628

: Https:// redirect to https://www in NGINX How do you redirect all non-www links to my website to https://www. I know that there are a lot of solutions for .htaccess but I haven't been able

@Mendez628

Posted in: #301Redirect #CanonicalUrl #Nginx #Redirects

How do you redirect all non-www links to my website to www. I know that there are a lot of solutions for .htaccess but I haven't been able to find anything sufficient for nginx.

At the moment all I have is

##
# Redirect non-www to www
##
server {
listen 80;
server_name example.com; # add other domains separated by a space as necessary
rewrite ^/(.*)$ www.example.com/ permanent;
}


which redirects:

example.com example.com example.com http://www.example.com


to www.example.com which is what I want, except that example.com doesn't redirect www.example.com
How do so how do I get to redirect to www.?

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Mendez628

2 Comments

Sorted by latest first Latest Oldest Best

 

@Margaret670

Since my last answer using the "if" statement is not recommended in most cases, I came up with another solution which seems to be working perfectly.

What I did was create another server block with www in the server_name and had my other server blocks redirect to it.

server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 www.example.com$request_uri; }

# HTTPS — proxy all requests to the Node app
server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
return 301 www.example.com$request_uri;
# Use the Let’s Encrypt certificates
...
}

server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
# Use the Let’s Encrypt certificates
...
}

10% popularity Vote Up Vote Down


 

@Sarah324

So far what I came up with is a simple if statement under port 443 to check if the domain is non-www and then redirect to www

server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
if ($host = example.com) {
return 301 www.example.com$request_uri; }

# Use the Let’s Encrypt certificates
...


I'm no expert but I don't think this is the best solution because it will be doing an if statement for every request if I'm right?

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme