在 .htaccess 中需要特定的 URL RewriteRule

Need a specific URL RewriteRule in .htaccess

我是设置 .htaccess 的新手,希望对我的问题有所帮助。

如果用户点击以下URL(原URL):

http://www.example.com/somepage/something

我希望它重定向到:

http://www.example.com/somepage

并在浏览器中保留原始 URL。

到目前为止,我有以下内容:

RewriteRule ^somepage/(.*)$ /somepage [R=301]

但是,它不起作用。

我如何让它工作?

编辑:

这是我的 .htaccess 文件现在的样子:

# do not allow anyone else to read your .htaccess file
<Files .htaccess>
deny from all
</Files>

# forbid viewing of directories
Options All -Indexes

# hide this list of files from being seen when listing a directory
IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*

# disable the server signature- helps with preformance
ServerSignature Off

RewriteEngine On
#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ .html [L,QSA]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ / [R=301,L]

RewriteRule ^somepage/(.*)$ /somepage [R=301]

这条规则有问题:

RewriteRule ^somepage/(.*)$ /somepage [R=301]

有两个原因:

  1. 由于您不希望 URL 更改,因此不得在此规则中使用 R=301 标志。
  2. 更大的问题是你的正则表达式 ^somepage/(.*)$ 也会匹配 /somepage/ 而你需要匹配 /somepage/something.

要解决此问题,请像这样获取完整的 .htaccess:

# do not allow anyone else to read your .htaccess file
<Files .htaccess>
deny from all
</Files>

# forbid viewing of directories
Options All -Indexes

# hide this list of files from being seen when listing a directory
IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*

# disable the server signature- helps with preformance
ServerSignature Off

RewriteEngine On
RewriteBase /

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/ [NC]
RewriteRule ^(.+?)\.html$ / [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/\.html -f [NC] 
RewriteRule ^([^/.]+) .html [L]