htaccess redirect not existing file (404) as 302 to another

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

htaccess redirect not existing file (404) as 302 to another

Post by lovelf »

Doing pagination on a site through lazy load:

I would want to redirect

dir/546/index.html
if it does not exist

to

/dir/index.html
546/ is of any numeric value.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: htaccess redirect not existing file (404) as 302 to anot

Post by Celauran »

Perhaps something like this?

Code: Select all

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/dir/([0-9]+)/?(index\.html)?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /dir/index.html [R=302,L,NC]
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Re: htaccess redirect not existing file (404) as 302 to anot

Post by lovelf »

Yes, almost there, how might use /dir/ as wildcard for any directory name.

Thanks
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: htaccess redirect not existing file (404) as 302 to anot

Post by Celauran »

Perhaps with another capture group? Replace ^/dir with the appropriate regex and use a lookback rather than a hardcoded value for the rewrite.
Post Reply