Reputation: 3128
I have http:// and https:// on the same host like the following:
server {
listen 80;
listen 443 ssl;
...
...
}
What I need to do is redirecting users who access my shop to https://
. The problem is I have many languages:
https://example.com/en/shop
https://example.com/fr/shop
I tried this and it didn't work (nginx: configuration file /etc/nginx/nginx.conf test failed)
:
if ($server_port = 80) {
location (en|fr)/shop {
rewrite ^ https://$host$request_uri permanent;
}
}
Upvotes: 17
Views: 33195
Reputation: 6075
It would also be more of an Nginx best practice to do a 301 redirect instead of using the if statement (see Server name on http://wiki.nginx.org/Pitfalls). I created a gist with an nginx.conf
configured for SSL, Rails and Unicorn
https://gist.github.com/Austio/6399964
Here would be the relevant section for yours.
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
Upvotes: 47
Reputation: 497
another way with error_page 497
server {
listen 80;
listen 443;
ssl on;
error_page 497 https://$host$request_uri;
ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
...
Upvotes: 2
Reputation: 172
Or better yet, avoiding the hardcoded server name
server {
listen 80;
rewrite (.*) https://$http_host$1 permanent;
}
Upvotes: 11
Reputation: 413
Ideally, avoiding if statements while preserving the trailing path:
server {
listen 80;
server_name example.com;
rewrite (.*) https://example.com$1 permanent;
}
permanent takes care of the 301.
Upvotes: 2
Reputation:
In order to use regular expressions for matching location
s, you need to prefix the expression with either ~
or ~*
:
if ($server_port = 80) {
location ~ (en|fr)/shop {
rewrite ^ https://$host$request_uri permanent;
}
}
From the documentation:
To use regular expressions, you must use a prefix:
"~"
for case sensitive matching"~*"
for case insensitive matching
Since nginx does't allow location
blocks to be nested inside of if
blocks, try the following configuration:
if ($server_port = 80) {
rewrite ^/(en|fr)/shop https://$host$request_uri permanent;
}
Upvotes: 6