Nginx在特定位置转发到https

时间:2015-04-11 09:23:59

标签: nginx configuration

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

  
      
  1. 转发www到非www
  2.   
  3. 将https转发至http
  4.   
  5. 仅使用带有模式' secure'
  6. 的uri上的https   

以下代码达到了目标,但在第3点,Chrome会显示空白页面并显示错误'此网页有一个重定向循环'。任何人都可以告诉适当的配置,和/或任何更好的代码?

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

   #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;
       }
    }

1 个答案:

答案 0 :(得分:0)

通过在应用程序级别执行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);

});