【问题标题】:Nginx forward to https at specific locationNginx 在特定位置转发到 https
【发布时间】:2015-04-11 09:23:59
【问题描述】:

在我的 nginx 配置中,我打算达到以下目的:

  1. 将 www 转发到非 www
  2. 将 https 转发到 http
  3. 仅在具有“安全”模式的 uri 上使用 https

下面的代码达到了目标,除了在第 3 点,chrome 显示空白页并显示错误“此网页具有重定向循环”。任何人都可以为此提供正确的配置和/或任何更好的代码?

请注意,我在下面的代码中写了 h--p,因为如果我写 http,SO 就不会发布。

   #redirect www to non-www
   server {
       listen 80;
       server_name www.mydomain.org;
       return 301 h--p://mydomain.org$request_uri;
   }

   #redirect https to http, for both www and non-www
   #but process https for uri with pattern 'secure'
   server {
       ssl_certificate /home/mydomain/ssl.cert;
       ssl_certificate_key /home/mydomain/ssl.key;

       listen 443 ssl;
       server_name www.mydomain.org mydomain.org;
       root /home/mydomain/public_html/mydomain/public;
       index index.php;

       access_log /var/log/virtualmin/mydomain.org_access_log;
       error_log /var/log/virtualmin/mydomain.org_error_log;

       #if has pattern 'secure', just process
       #---problem is here, chrome result 'This webpage has a redirect loop'---
       location ~ ^/(secure) {

            try_files $uri $uri/ /index.php$is_args$args;

            location ~ \.php$ {
               try_files $uri =404;
               fastcgi_pass   127.0.0.1:9000;
               fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
               include        fastcgi_params;
           }
       }

       return 301 h--p://mydomain.org$request_uri;
   }

   server {
       listen 80;
       server_name mydomain.org;
       root /home/mydomain/public_html/mydomain/public;
       index index.php;

       access_log /var/log/virtualmin/mydomain.org_access_log;
       error_log /var/log/virtualmin/mydomain.org_error_log;

       #rewrite to https if has pattern secure
       location ~ ^/(secure) {
           #rewrite ^(.*) h--ps://$host$1 permanent;
           return 301 h--ps://mydomain.org$request_uri;
       }

       location / {
           try_files $uri $uri/ /index.php$is_args$args;
       }

       location ~ \.php$ {
           try_files $uri =404;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
           include        fastcgi_params;
       }
    }

【问题讨论】:

    标签: nginx configuration


    【解决方案1】:

    通过在应用程序级别进行 ssl 重定向结束

    Route::filter('check.ssl', function()
    {
        $segment = Request::segment(1);
    
        if ( ( $segment == 'secure') && ( !Request::secure() ) )
            return Redirect::secure(Request::getRequestUri());
        else if ( ( $segment != 'secure') && ( Request::secure() ) )
            return Redirect::to(Request::path(), 302, array(), false);
    
    });
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2023-03-10
      • 1970-01-01
      • 2017-07-10
      相关资源
      最近更新 更多