Reputation: 1785
Again a nginx redirect problem. I need my website to be accessible only over https and always with subdomain www (or app or api). Is there a way the following configuration accept https://example.com (without www) ? Because that's what I see right now, without being able to explain why... I just add that there's no other server section on nginx configuration.
server {
listen 80;
server_name ~^(?<subdomain>www|app|api)\.example\.com$;
index index.html index.htm;
return 301 https://$subdomain.example.com$request_uri;
}
server {
listen 443 ssl;
server_name ~^(?<subdomain>www|app|api)\.example\.com$;
root /var/www/html/pathToMyWebsite;
index index.php;
}
Edit: Here is what I ended up using thanks to @ivan:
# Redirects http://example.com & https://example.com to https://www.example.com
server {
listen 80;
listen 443 ssl; # Here is the trick - listen both 80 & 443.
# other ssl related stuff but without "ssl on;" line.
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
server_name ~^(?<subdomain>www|app|api)\.example\.com$;
index index.html index.htm;
return 301 https://$subdomain.example.com$request_uri;
}
server {
listen 443 default_server ssl;
server_name ~^(?<subdomain>www|app|api)\.example\.com$;
root /var/www/html/pathToMyWebsite;
index index.php;
}
notice the "default_server" I added on listen 443 default_server ssl;
Upvotes: 3
Views: 853
Reputation: 6709
First of all, using regexp in the nginx config usually is not a good solution. Almost always it's more reasonable to copy and paste config blocks or use include
statements since regexp introduces redundant complexity. Of course, it's kind of trade off what to use.
However, I have pretty the same usage pattern in my configs:
# Redirects http://example.com & https://example.com to https://www.example.com
server {
listen 80;
listen 443 ssl; # Here is the trick - listen both 80 & 443.
# other ssl related stuff but without "ssl on;" line.
server_name example.com;
return 301 https://www.example.com$request_uri;
}
# Redirects http://*.example.com to https://*.example.com
server {
listen 80;
server_name ~^.+\.example\.com$;
return 301 https://$host$request_uri;
}
server {
listen 443;
server_name ~^.+\.example\.com$;
ssl on;
# ...
}
Upvotes: 3