Mod 重写 - HTTPS 重定向导致 404 错误

问题描述

我有一个问题,我的 htaccess 文件导致 404 错误,而这些 URL 应该在添加 HTTPS 条件和规则时重写。删除 HTTPS 条件和规则后,所有规则都能正常工作。任何人都可以指出我正确的方向吗?

这是我的 .htaccess 文件

RewriteEngine ON

# All Projects Rule

RewriteRule ^projects/?$ all-projects.PHP [NC,QSA,L]

# Add Project Rule

RewriteRule ^projects/add/?$ add-new-project.PHP [NC,L]

# Assigned Projects Rule

RewriteRule ^projects/assigned/?$ assigned-projects.PHP [NC,L]

# Single Project Rule

RewriteRule ^projects/([^/]+)/([^/]+)/?$ single-project.PHP?id=$1&section=$2 [NC,L]

# Single Project Subfolders

RewriteRule ^(projects)/([^/]+)/([^/]+)/(.*)/?$ $1/$2/$3/?subfolder=$4 [NC,L]

# All Users Rule

RewriteRule ^users/([^/]+)/([^/]+)/?$ all-users.PHP?sort=$1&direction=$2 [NC,L]

# Add User Rule

RewriteRule ^users/add-user/?$ add-new-user.PHP [NC,L]

# Add Client Rule

RewriteRule ^users/add-client/?$ add-new-client.PHP [NC,L]

# Force HTTPS

<If "%{HTTP_HOST} == 'example.com'">
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</If>

此外,这里有一些原始 URL 的示例以及它们在应用规则后的样子

  1. all-projects.PHP?id=2&section=documents 变成 /projects/2/documents/

  2. add-new-user.PHP 变成 /users/add-user/

  3. all-users.PHP?sort=id&direction=asc 变成 /users/id/asc

解决方法

根据您所展示的努力/规则,请您尝试遵循规则。请将您的 htaccess 规则文件放在您的根目录中。

请确保在测试您的 URL 之前清除浏览器缓存。

RewriteEngine ON

# Force HTTPS
<If "%{HTTP_HOST} == 'example.com'">
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)/?$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</If>

# All Projects Rule
RewriteRule ^projects/?$ all-projects.php [NC,QSA,L]

# Add Project Rule
RewriteRule ^projects/add/?$ add-new-project.php [NC,L]

# Assigned Projects Rule
RewriteRule ^projects/assigned/?$ assigned-projects.php [NC,L]

# Single Project Rule
RewriteRule ^projects/([^/]+)/([^/]+)/?$ single-project.php?id=$1&section=$2 [NC,L]

# Single Project Subfolders
RewriteRule ^(projects)/([^/]+)/([^/]+)/(.*)/?$ $1/$2/$3/?subfolder=$4 [NC,L]

# All Users Rule
RewriteRule ^users/([^/]+)/([^/]+)/?$ all-users.php?sort=$1&direction=$2 [NC,L]

# Add User Rule
RewriteRule ^users/add-user/?$ add-new-user.php [NC,L]

# Add Client Rule
RewriteRule ^users/add-client/?$ add-new-client.php [NC,L]