需要在.htaccess特定的URL重写规则(Need a specific URL Rewrite

2019-10-21 21:07发布

我是新设立的.htaccess,我将不胜感激在我的问题有所帮助。

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

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

我希望它重定向到:

http://www.example.com/somepage

并保留原始网址在浏览器中。

到目前为止,我有以下几点:

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 ^(.+)$ $1.html [L,QSA]

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

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

Answer 1:

这条规则的问题是:

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$ /$1 [R=301,L]

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


文章来源: Need a specific URL RewriteRule in .htaccess