简体   繁体   中英

.htaccess redirect for .pdf/.doc file in the root folder

I am trying to create a rewrite rule similar to the one below

RewriteRule ^/?(.*+/.pdf)$ /site-content/import/uploads/$1 [L,R=301]

Any url request similar to

http://hostname/filename.pdf

Should redirect to

http://hostname/site-content/import/uploads/filename.pdf

But it should not redirect if the request file name is inside a sub folder and also it should not redirect the urls other than .pdf or .doc files

http://hostname/sub-page/filename.pdf
http://hostname/sub-page/sub/filename.pdf
http://hostname/sub-page
http://hostname/image.png

you can use this :

RewriteRule ^([^/.]+\.pdf)$ /site-content/import/uploads/$1 [R,L]

or this :

RedirectMatch ^/([^/.]+\.pdf)$ /site-content/import/uploads/$1

Clear your browser caches before testing this redirect.

EDIT:

The examples above redirect .pdf files only, to redirect both .pdf and .doc ,you can use this rule :

RewriteRule ^[^/.]+\.(pdf|doc)$ /site-content/import/uploads%{REQUEST_URI} [L,R]

Try regex ^/[^/]+\\.(pdf|doc)$ . Will match first / , any character that is not / and ends with .pdf or .doc .

Regex101 example


RewriteRule ^/([^/]+\.(?:pdf|doc))$ /site-content/import/uploads/$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