Need a specific URL RewriteRule in .htaccess

喜你入骨 提交于 2019-12-13 01:28:35

问题


I am new to setting up the .htaccess and I would appreciate some help in my problem.

If the user hits the following URL (original URL):

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

I want it to redirect to:

http://www.example.com/somepage

AND keep the original URL in the browser.

So far, I have the following:

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

But, it doesnt work.

How do I get this working?

EDIT:

Here is what my .htaccess file looks like right now:

# 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:


This rule is the problem:

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

for two reasons:

  1. Since you don't want URL to change you must not use R=301 flag in this rule.
  2. Bigger problem is that your regex ^somepage/(.*)$ will also also match /somepage/ and you needed to match /somepage/something.

To fix this issue have your full .htaccess like this:

# 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]


来源:https://stackoverflow.com/questions/28500941/need-a-specific-url-rewriterule-in-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!