【问题标题】:.htaccess for one url only.htaccess 仅适用于一个网址
【发布时间】:2023-04-04 18:29:01
【问题描述】:

我正在尝试将 一个 特定的 url,比如说 /admin,从我的域重定向到 http,而其他的都应该重定向到 https。示例:

Works:

http://example.com -> https://example.com
http://example.com/with-url -> https://example.com/with-url
https://example.com/admin -> http://example.com/admin

Does not work:

What I get (redirects from https to http, if under /admin): 
    https://example.com/admin/anything-below-here -> http://example.com/admin/anything-below-here

What I want (to stay on https):
    https://example.com/admin/anything-below-here -> https://example.com/admin/anything-below-here

这是我目前得到的:

RewriteEngine On

# force https:// for all except /admin    
RewriteCond %{HTTPS} off  
RewriteCond %{THE_REQUEST} !/admin [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for /admin URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /admin [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# all the others
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

谁能告诉我我在这里缺少什么?非常感谢!

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您的正则表达式是贪婪的,所以/admin/something 匹配/admin,因此在admin 内从https 重定向到http。

    尝试使用/admin[/]*$ 来指定仅/admin 和/admin/ 应该重定向到http,而不是/admin/something

    为了检查实际请求 URI 是否在 admin 之后结束,您还需要切换到 %{REQUEST_URI},而不是在 URI 之后包含数据的 %{THE_REQUEST}(例如,HTTP/1.1)。

    试试看:

    RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]
    

    如果/admin 不在%{THE_REQUEST} 中,您不需要更改另一个检查,因为它仍然有效。

    完整的代码如下所示:

    # force https:// for all except /admin
    RewriteCond %{HTTPS} off  
    RewriteCond %{REQUEST_URI} !^/admin[/]*$ [NC]
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # force http:// for /admin URLs
    RewriteCond %{HTTPS} on
    RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]
    RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # all the others
    RewriteBase /                         
    RewriteCond %{REQUEST_FILENAME} !-f                      
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
    

    【讨论】:

    • 我添加了那个位,但这也不起作用 - 它让我现在可以同时使用 http 和 https 访问 /admin。 RewriteCond %{THE_REQUEST} !/admin[/]*$ [NC] RewriteCond %{THE_REQUEST} /admin[/]*$ [NC](我跳过了中间的行 - 这不是我现在在 .htaccess 中的全部内容)。
    • 啊,是的,这是因为你使用 %{THE_REQUEST} 并且在请求 uri 之后有一些东西...(例如 HTTP/1.1)所以 $ 不只是在 admin 之后。
    • 不幸的是,无论有没有斜线,它都没有做任何事情。它也没有重定向到 http。
    • RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC] 在我的本地服务器上工作
    • 确保每次尝试新的东西时清空浏览器缓存,因为重定向已缓存
    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多