Mod Rewrite 500服务器错误问题

时间:2016-01-08 13:30:46

标签: php .htaccess mod-rewrite

概述

我正在尝试改写:

  • http://www.foo.com/bar到安全版https://www.foo.com/bar,然后
  • https://www.foo.com/barhttps://www.foo.com/index.php?location=bar

我的index.php页面只输出$_GET个变量。

代码

.htaccess

RewriteEngine On
RewriteBase /
RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]
RewriteRule ^([^/]*)$ /?location=$1 [L]

index.php

<?php print_r($_GET); exit; ?>

问题

  1. 如果我访问www.foo.com/bar,我会看到 500服务器错误
  2. 如果我注释掉处理$_GET“位置”变量的规则并访问foo.com,则不会重定向到网站的安全版本。
  3. 更新

    .htaccess

    RewriteEngine on
    
    # if https is off (it is on)
    #RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
    
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]
    

    访问以下结果会导致重定向循环错误:

    • www.foo.com/bar
    • www.foo.com/index.php?location=bar
    • www.foo.com/?location=bar
    • www.foo.com?location=bar

    但是,如果我注释掉这一行:

    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
    

    页面按预期加载:

      

    数组([location] =&gt; bar)

    这让我相信问题在于HTTPS重定向,我该如何解决?

1 个答案:

答案 0 :(得分:3)

此规则是问题:

RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]

语法是

RewriteRule matching-pattern target [flags]

此外,您需要在两个规则中RewriteCond以避免规则循环。

您可以使用以下代码替换代码来修复它:

DirectoryIndex index.php
RewriteEngine on

# if https is off
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]