需要.htaccess中的特定URL RewriteRule

时间:2015-02-13 13:39:43

标签: regex apache .htaccess mod-rewrite rewrite

我是设置.htaccess的新手,我很感激我的问题有所帮助。

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

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]

1 个答案:

答案 0 :(得分:1)

此规则是问题:

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

有两个原因:

  1. 由于您不希望更改网址,因此您不得在此规则中使用R=301标记。
  2. 更大的问题是,您的正则表达式^somepage/(.*)$也会匹配/somepage/,您需要匹配/somepage/something
  3. 要修复此问题,请使用以下完整的.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]