简体   繁体   中英

htaccess 301 redirect and rewrite urls

I just moved a site and some of the old pages are still being viewed. Here is an example of the old url structure:

http://mydomain.com/text_version/personal_and_people_development.php

And how I want it to redirect to:

http://mydomain.com/personal-and-people-development/

What I want it to do is 301 redirect any page in the folder /text_version/ by stripping the /text_version piece of the path, convert all underscores to hyphens and replace the .php file extension with a trailing slash.

Also note I allow the user to use the www. subdomain, and may require https:// access in future.

Is it possible to do a folder wide 301 redirect like so or do I have to specify each individual page? If so can someone give me a pointer as I am not very good with mod_rewrite or regex .

Update: This is what I have managed to piece together so far due to stringing together other people's code. This is stored in a .htaccess file located in the /text_version subfolder.

Options +FollowSymlinks
RewriteEngine on

RewriteBase /

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L, QSA]

RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://mydomain.com/$1/ [L,R=301]

RewriteRule (.*)_(.*) $1-$2 [N]

However this converts:

http://mydomain.com/text_version/personal_and_people_development.php

to

http://mydomain.com/personal-and-people-development.php/

After a lot of messing about, and not understanding most of it I managed to piece together this solution:

Options +FollowSymlinks
RewriteEngine on

RewriteBase /
RewriteRule (.*)_(.*) $1-$2 [N]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ .*\.php.*$
RewriteRule ^(.*)\.php(.*)?$ /$1$2 [R=301,L]

RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ ^(www.)?mydomain.com/$1/ [L,R=301]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM