.htaccess规则 - 重定向太多

时间:2017-10-04 10:50:07

标签: apache .htaccess redirect mod-rewrite

我正在尝试使用htaccess文件完成两件事:

  1. 仅在2个目录以外的所有目录上强制执行https,仅当从prod url访问时(在开发时没有https)
  2. 重定向index.php
  3. 中任何不存在的网址

    这就是我所拥有的:

    RewriteEngine On
    # Redirect all http to https
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} myserver\.com$ [NC]
    RewriteRule ^(api|images)($|/) - [L]
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    # The following rule tells Apache that if the requested filename
    # exists, simply serve it.
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    # The following rewrites all other queries to index.php. The 
    # condition ensures that if you are using Apache aliases to do
    # mass virtual hosting, the base path will be prepended to 
    # allow proper resolution of the index.php file; it will work
    # in non-aliased environments as well, providing a safe, one-size 
    # fits all solution.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
    

    当我添加第一位(https强制执行)时,我得到“太多重定向”错误。任何想法为什么?

2 个答案:

答案 0 :(得分:1)

RewriteRule仅适用于下一个http->https。您RewriteEngine On # Redirect all http to https RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} myserver\.com$ [NC] RewriteCond %{THE_REQUEST} !\s/+(?:api|images)[/?\s] [NC] RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] # The following rule tells Apache that if the requested filename # exists, simply serve it. RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] # The following rewrites all other queries to index.php. The # condition ensures that if you are using Apache aliases to do # mass virtual hosting, the base path will be prepended to # allow proper resolution of the index.php file; it will work # in non-aliased environments as well, providing a safe, one-size # fits all solution. RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$ RewriteRule ^(.*) - [E=BASE:%1] RewriteRule ^ %{ENV:BASE}index.php [L] 的重定向规则是无条件的,会导致重定向循环。

这样做:

l = [4,3,2,5,6,4,6]
# split l in chunks -> e.g. [[4,3,2], [5,6,4,6]] 
chunks = [[4,3,2], [5,6,4,6]]

with open('file.txt', 'w') as f: 
    for i,chunk in enumerate(chunks):
        if i!=0:
            f.write('\n'+','.join(str(i) for i in chunk))
        else:
            f.write(','.join(str(i) for i in chunk))

# read data back in ls as integers
ls = []
with open('file.txt', 'r') as f:
    lines = f.read().splitlines()
    for line in lines:
        ls += map(int,line.split(','))

print ls

答案 1 :(得分:0)

我相信这部分应该更像:

RewriteRule ^(api|images)($|/) - [L]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} myserver\.com$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]