组合 Nginx 重定向规则

组合 Nginx 重定向规则

我刚刚将 Rails 应用程序从 Apache/Passenger 服务器迁移到新的 Nginx/Unicorn 服务器,但在执行必要的重定向时遇到了一些问题。

到目前为止,该配置(在我之前由其他人设置)已成功将访问重定向http(s)://example.com/http://www.example.com/

我遇到的问题是将端口 80 上的所有其他访问重定向到 443。例如,http://login.example.com/->https://login.example.com/

我快速浏览了 Nginx 文档,以后我会阅读更多相关内容。但现在我只需要让它工作起来,所以如果有人能告诉我如何修改以下配置,我将不胜感激:

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.
}

提前谢谢了!

答案1

经过一些反复试验后(在一些帮助下以nginx -t确保我没有破坏任何东西)我终于使用这个配置让它工作了:

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.
}

相关内容