首页 > 解决方案 > 如何使用 htaccess 将斜杠附加到 URL?

问题描述

我想从 重定向author/$usernameauthor/$username/$username是作者的用户

这是我的.htaccess内容:

RewriteEngine on
RewriteRule ^author/([A-Za-z0-9-\+]+)/?$ author/index.php?username=$1 [NC,L,QSA]
RewriteRule ^authorpost/([A-Za-z0-9-\+]+)/postid/([0-9]+)/?$ author/index.php?username=$1&postid=$2 [NC,L,QSA]

我需要如何更改它?

标签: apache.htaccessmod-rewrite

解决方案


那么,如果我理解正确,您只需要在 URL 上附加一个斜杠/author/<username>吗?

在文件顶部尝试这样的.htaccess操作:

RewriteRule ^(author/[A-Za-z0-9+-]+)$ /$1/ [R=302,L]

字符类+内部没有特殊含义,因此不需要转义。连字符 ( -) 应位于字符类的开头或结尾,以匹配文字连字符(无需转义)。

在以下重写中,您现在可以强制使用尾部斜杠,而不是使其成为可选。例如:

RewriteRule ^author/([A-Za-z0-9+-]+)/$ author/index.php?username=$1 [NC,L,QSA]

概括

RewriteEngine On

# Append trailing slash if omitted
RewriteRule ^(author/[A-Za-z0-9+-]+)$ /$1/ [NC,R=302,L]

# Internal rewrites...
RewriteRule ^author/([A-Za-z0-9+-]+)/$ author/index.php?username=$1 [NC,L,QSA]
RewriteRule ^authorpost/([A-Za-z0-9+-]+)/postid/([0-9]+)/?$ author/index.php?username=$1&postid=$2 [NC,L,QSA]

理想情况下,您应该避免在内部重写NC时使用该标志,以避免潜在的重复内容。至少,它应该是不必要的。


推荐阅读