I'm trying to redirect all HTTP traffic to HTTPS. The web server I'm using is nginx. This is the server block I'm using to do the redirect.

server {
    listen      80;
    rewrite ^ https://$server_name$request_uri? permanent;

This successfully redirects URLs like http://localhost to https://localhost. However, for URLs like http://localhost/table/ I get redirected to https://table which is incorrect. I would like it to re-direct to https://localhost/table/

Any help would be much appreciated.

Update: It seems that the rewrite scheme has a problem with trailing slashes. For example, http://localhost/table gets correctly redirected but http://localhost/table/ does not.

  • can you try to hardcode the server name like https:// localhost$request_uri? permanent; and check if it works – Hex Nov 21 '12 at 12:49
  • Hard coding the server name to localhost fixes it. However, other machines cannot access it as they get redirected to localhost, instead of the server name. – CadentOrange Nov 21 '12 at 13:33
  • Ok, so nginx is not getting $server_name. Set the servername $server_name domain.com – Hex Nov 21 '12 at 14:54
  • I don't think that's the problem. To test it out, I've set server_name and I still get the same behaviour. It looks like the rewrite rule is getting confused and is treating /table/ as the server name. – CadentOrange Nov 21 '12 at 15:03
  • Are you sure that your problem isn't in your https server configuration? – VBart Nov 21 '12 at 16:59
server {
    listen 80;
    rewrite 301 https://$host$request_uri;


| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.