Reputation: 17835
I'm trying to redirect www to non-www on elastic beanstalk, but I can't find any info on how to do that with nginx.
I have a location config that redirects http to https. Is there a way I can do this inside that config? I'd have to override the base nginx config to add a server
config (which is the recommended way to do it according to the nginx docs), which I'd rather not do if I don't have to.
location / {
set $redirect 0;
if ($http_x_forwarded_proto != "https") {
set $redirect 1;
}
if ($http_user_agent ~* "ELB-HealthChecker") {
set $redirect 0;
}
if ($redirect = 1) {
return 301 https://$host$request_uri;
}
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Upvotes: 3
Views: 601
Reputation: 732
As I commented, I would use different server blocks. If you don't want, I would use the logic on $redirect as a boolean, and redirect hardcoding the $host, you want it without www anyway, don't you? Would this fit in what you want to do?:
location / {
set $redirect 0;
if ($http_x_forwarded_proto != "https") {
set $redirect 1;
}
if ($host != "www.example.com") {
set $redirect 1;
}
if ($http_user_agent ~* "ELB-HealthChecker") {
set $redirect 0;
}
if ($redirect = 1) {
return 301 https://example.com$request_uri;
}
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
like this you end with only 1 redirect to the correct scheme://host . Or is there anything else you are configuring in this location block that I need to consider?
I hope I helped.
Upvotes: 2