首页 > 解决方案 > 使用 .htaccess 处理不存在的路径并将 http 转换为 https

问题描述

我正在尝试使用 .htaccess 实现以下目标

1 - 将所有 http 请求转换为 https 2 - 捕获任何不存在的路径,并重定向到现有路径,通过某种方式(作为查询字符串、哈希、通过信封或 post 变量)传递不存在的路径以进行解释。3 - 能够针对特定文件夹执行上述两项操作。

目前,我通过将不存在的路径作为哈希传递来使#2 工作,该哈希由客户端脚本解释:

RewriteEngine On
RewriteBase /SomeSubFolder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ \#$1 [L,R=301,NE]

它适用于 http://[somedomain.com]/[ExistingPath]/[NonExistingPath]

变成

http://[somedomain.com]/[ExistingPath]/#[NonExistingPath]

(即,不存在的路径成为标记到现有路径的哈希,随后通过 JS 进行解释)

如果有一种不那么古怪的方法可以做到这一点,我会全神贯注。

到目前为止,我还无法将 http 请求转换为 https 并同时保护上述功能。

标签: .htaccess

解决方案


您可以使用以下内容:

RewriteEngine On
RewriteBase /SomeSubFolder/
#http to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
#redirect non-existant path
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ \#$1 [L,R=301,NE]

当您确定规则工作正常时,更改RR=301https 规则以使重定向永久化(浏览器和搜索引擎缓存)。


推荐阅读