Nginx with ssl always returning 301

301-redirectnginxssl

I am trying to setup nginx with ssl, to serve some static HTML and the output of some Python scripts (through uwsgi). It works fine with HTTP, but I am not able to make it run on HTTPS, as nginx is returning a "301 Moved Permanently" matter the URI (i.e., even for those that do not exist).

I am currently using a self-signed certificate and my idea is to force HTTPS connections. What am I doing wrong? Does it look like an nginx configuration problem?

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

server {
  listen 443 ssl;
  server_name myserver.com;
  ssl_certificate /srv/ssl/nginx.pem;
  ssl_certificate_key /srv/ssl/nginx.key;
  location / {
    rewrite ^ https://$server_name$request_uri? permanent;
  }
}

(obviusly, myserver.com stands for the actual server name).

Edit: Typos.

Best Answer

Your rewrite rule is in the wrong place: it applies (only) to the server block which does SSL already. Your browser might have been already complaining about a never-ending redirect.

Put the rewrite rule in the server block which listens on Port 80, without SSL.