This is my Nginx config:

upstream app_server {
  # Bindings to the Gunicorn server
  server fail_timeout=0;

server {
  listen 80;
  server_name "~^www\.(.*)$";
  return 301 https://$host$request_uri;

server {
  access_log path_to_nginx-access.log;
  error_log path_to_nginx-error.log;

  listen 443 ssl;
  server_name _;
  ssl_certificate path_to_nginx.crt;
  ssl_certificate_key path_to_nginx.key;

  client_max_body_size 4G;
  keepalive_timeout 5;
  root path_to_root;

  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $host;
    proxy_redirect off;

    if (!-f $request_filename) {
      proxy_pass http://app_server;
  error_page 500 502 503 504 /500.html;
  location = /500.html {
    root path_to_templates;

with this config I can redirect:

How do I make my server redirect https www to https non-www. Keep in mind that I need to handle multiple domains with the same Nginx server (vide server_name).


| improve this question | | | | |
  • With https, you need to have a certificate that covers all the domains you are planning to redirect. You can have a certificate that covers multiple domains, but you need to know all the domains when ordering the certificate. However, it might be possible that nginx cannot use similar server_name setup with https as you use with http, because the domain name is negotiated in a different spot with https. So, this might be impossible to achieve. – Tero Kilkanen Mar 21 '16 at 20:26
  • Sure! I got you. How would I solve it for one domain only? – MatheusJardimB Mar 21 '16 at 20:29

For a single domain you can achieve it like this:

server {
    listen 443;
    server_name www.domain.com;
    ssl_certificate path_to_certificate;
    ssl_certificate_key path_to_key;

    return 301 https://domain.com$request_uri;
| improve this answer | | | | |
  • my certificate only supports domain.com (without wildcards). By adding the code above I'm getting "invalid certificate error". Any tips? – MatheusJardimB Mar 21 '16 at 21:24
  • In that case you need to get a certificate that is valid for both domain.com and www.domain.com. Usually CAs give you certificates that are valid for both. You need to contact your CA and ask how to get a certificate that is valid for both. – Tero Kilkanen Mar 21 '16 at 21:53

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.