将所有URL从HTTP重定向到HTTPS(使用seo URL)

时间:2016-12-06 02:28:08

标签: .htaccess nginx

我在.htaccess中使用的代码:

RewriteEngine On 
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
RewriteRule ^(.*)$ index.php [QSA,L]

我想重写它以更改所有指向https://

的链接

当我添加

RewriteEngine On 
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
RewriteRule ^(.*)$ index.php [QSA,L]
RewriteCond %{HTTP_HOST} ^localhost [NC] 
RewriteRule ^(.*)$ https://localhost/$1 [L,R=301]

给我错误,重定向太多。

或尝试更改时

RewriteEngine On 
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
RewriteRule ^(.*)$ https://localhost/ [QSA,L]

也有太多的重定向。

我也在使用nginx的apache。 nginx代码(也许可以通过nginx做?)

server {
    listen      127.0.0.1:80;
    server_name localhost;
    error_log  /var/log/httpd/domains/localhost.error.log error;

    location / {
        proxy_pass      http://127.0.0.1:8080;
        location ~* ^.+\.(jpeg|jpg|gif|bmp|ico|svg|tif|tiff|css|js|htm|html|ttf|otf|webp|woff|txt|csv|rtf|doc|docx|xls|xlsx|ppt|pptx|odf|odp|ods|odt|pdf|psd|ai|eot|eps|ps|zip|tar|tgz|gz|rar|bz2|7z|aac|m4a|mp3|mp4|ogg|wav|wma|3gp|avi|flv|m4v|mkv|mov|mpeg|mpg|wmv|exe|iso|dmg|swf)$ {
            root           /home/admin/web/localhost/public_html;
            access_log     /var/log/httpd/domains/localhost.log combined;
            access_log     /var/log/httpd/domains/localhost.bytes bytes;
            expires        4h;
            try_files      $uri @fallback;
        }
    }

    location /error/ {
        alias   /home/admin/web/localhost/document_errors/;
    }

    location @fallback {
        proxy_pass      http://127.0.0.1:8080;
    }

    location ~ /\.ht    {return 404;}
    location ~ /\.svn/  {return 404;}
    location ~ /\.git/  {return 404;}
    location ~ /\.hg/   {return 404;}
    location ~ /\.bzr/  {return 404;}

    include /home/admin/conf/web/nginx.localhost.conf*;
}

1 个答案:

答案 0 :(得分:2)

对于Apache重写,您可以使用%{HTTPS}检查它是否为HTTPS URL。

RewriteCond %{HTTPS} off
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

当然你也可以用nginx来做。

由于http访问端口80,默认情况下https访问端口443,您只需在端口80服务器块中设置重定向到https url。

像这样。

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443;
    ssl on;
    # The rest of your config
}