Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How rewrite url in htaccess

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

like image 690
Carl Rguz Avatar asked Dec 07 '25 03:12

Carl Rguz


1 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]
like image 163
anubhava Avatar answered Dec 08 '25 16:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!