How rewrite url in htaccess

Viewed 395

Good Morning,

I have documents within the structure of my website, which are accessed with the following url format:

http://example.com/docs/files/123/mydoc.pdf

http://example.com/docs/files/475/otherdoc.pdf

I want when a url of the above type is accessed, it is renamed with the following format:

http://example.com/123/mydoc

http://example.com/475/otherdoc

I have the following rules in the htaccess

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
RewriteRule ^/docs/files/([0-9]+)/([a-zA-Z0-9-]+)\.([a-zA-Z-]+) /$1/$2 [QSA,L]
</IfModule>

If I type in the browser

http://example.com/docs/files/123/mydoc.pdf

It doesn't change the url to

http://example.com/123/mydoc

What am I doing wrong?

Thanks

2 Answers

You may try these rules in your site root .htaccess:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+files/(\S+)\.pdf[?\s] [NC]
RewriteRule ^ /%1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/files/$1.pdf -f
RewriteRule ^(.+?)/?$ files/$1.pdf [L]

With your shown samples, could you please try following. Please make sure you clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteCond %{THE_REQUEST} \s(/files/.*)\.pdf\s [NC]
RewriteRule ^ http://%{HTTP_HOST}%1 [R=301,NE]
RewriteRule ^(.*)/?$ files/$1.pdf [L]
Related