Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I've just migrated a Rails app from an Apache/Passenger server to a new Nginx/Unicorn server and I'm having some trouble getting the necessary redirects to work.

So far the config (which was set up by someone else before me) is successfully redirecting visits to http(s)://example.com/ to http://www.example.com/

The bit I'm having trouble with is redirecting every other visit on port 80 to 443. For example, http://login.example.com/ -> https://login.example.com/

I've had a quick look through the Nginx docs and, in time, I'll be doing a lot more reading up on it. But right now I just need to get this working so I'd really appreciate it if someone could show me how I should modify the config below:

upstream app_server {
  server unix:/tmp/unicorn.mydomain.sock fail_timeout=0;
}

server {
  server_name ~^www\..*\.mydomain.com$;
  rewrite ^(.*) http://mydomain.com$1 permanent;
}

server {
  listen 80 deferred;
  listen 443 default ssl;

  server_name .mydomain.com;

  # Config for app directories, SSL certs, logs etc.
}

Many thanks in advance!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

After a bit of trial and error (with some help from nginx -t to make sure I didn't break anything) I finally got it working with this config:

upstream app_server {
  server unix:/tmp/unicorn.mydomain.sock fail_timeout=0;
}

server {
  server_name ~^www\..*\.mydomain.com$;
  rewrite ^(.*) http://mydomain.com$1 permanent;
}

server {
  listen 80;

  server_name .mydomain.com;

  rewrite ^ https://$host$request_uri? permanent;
}

server {
  listen 443 default ssl;

  server_name .mydomain.com;

  # Config for app directories, SSL certs, logs etc.
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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