I have a fairly complex Ruby application that gives customers a dashboard available under their own chosen subdomain. i.e.: http://mycompany.app.com
, http://myproject.app.com
.
I also have the product website running on the root domain (i.e., http://app.com
) and I've bought and configured an SSL certificate with Nginx and it's working as expected, but that leaves me with the following problem scenario:
I need to redirect all non-https traffic to the https version of the page, except for any requests going to any of the subdomains. What makes it tricky is that I do however need to redirect the www version of the site to the non-www version.
http://app.com -> https://app.com
http://www.app.com -> https://app.com
http://nike-admin.app.com !-> https://nike-admin.app.com
Here's what I have come up with so far in nginx.conf for this app (real name replaced by app
):
upstream unicorn_server {
server unix:/var/www/<app>/tmp/sockets/unicorn.sock fail_timeout=0;
}
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
server_name <app>.co;
location / {
rewrite ^ https://$server_name$request_uri permanent;
}
}
server {
server_name <app>.co;
root /var/www/<app>.co/public;
client_max_body_size 4G;
keepalive_timeout 70;
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/<app>.crt;
ssl_certificate_key /etc/nginx/ssl/<app>.key;
location / {
try_files $uri @app;
}
location @app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn_server;
}
}
In the first server{} block, I explicitly listen for any connection on port 80 and redirect those to the https version, but that's a double-edged sword as the SSL certificate only covers the apex domain. I don't want requests on any subdomains other than www to be redirected to the https equivalent.
I could potentially use regex, but from what I've seen online, but it seems to be frowned upon?
Is there any other way to do this?