How to redirect all HTTP requests to HTTPS

前端 未结 26 2206
小鲜肉
小鲜肉 2020-11-22 00:40

I\'m trying to redirect all insecure HTTP requests on my site (e.g. http://www.example.com) to HTTPS (https://www.example.com). I\'m using PHP btw.

26条回答
  •  無奈伤痛
    2020-11-22 00:53

    The best solution depends on your requirements. This is a summary of previously posted answers with some context added.

    If you work with the Apache web server and can change its configuration, follow the Apache documentation:

    
        ServerName www.example.com
        Redirect "/" "https://www.example.com/"
    
    
    
        ServerName www.example.com
        # ... SSL configuration goes here
    
    

    But you also asked if you can do it in a .htaccess file. In that case you can use Apache's RewriteEngine:

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
    

    If everything is working fine and you want browsers to remember this redirect, you can declare it as permanent by changing the last line to:

    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    But be careful if you may change your mind on this redirect. Browsers remember it for a very long time and won't check if it changed.

    You may not need the first line RewriteEngine On depending on the webserver configuration.

    If you look for a PHP solution, look at the $_SERVER array and the header function:

    if (!$_SERVER['HTTPS']) {
        header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); 
    } 
    

提交回复
热议问题