: 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
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.?
More posts by @Mendez628
2 Comments
Sorted by latest first Latest Oldest Best
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
...
}
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?
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.