Irfan
Irfan

Reputation: 7059

Redirect only if file does not exist

I have a use case where there can be HTML or PHP file in a folder but the user will only access HTML file. I was looking for htaccess redirect only if HTML file is missing. After some research, I tried below code which always redirect to php file no matter file exists or not. So if there is a file test.html then no need to redirect to test.php.

RewriteEngine on
RewriteCond ^wp-content/uploads/(.*)/test.html !-f
RewriteRule ^wp-content/uploads/(.*)/test.html?$ wp-content/uploads/$1/test.php [NC,L]

Upvotes: 2

Views: 1508

Answers (2)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

I think in your case , you want to make the priority for .html files then , if missing , to .php and force user even they request .php to access .html unless not found , so try the following code :

RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.php[\s?/] [NC]
RewriteRule ^ /%1%2 [R,L,NE]
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$      /$1.html   [L]
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$      /$1.php   [L]

The code above will passes all .html and check requests without extensions first with .html and also remove .php requests and check if there is .html with same name otherwise , go as it is .

Upvotes: 1

anubhava
anubhava

Reputation: 785156

-f needs full filesystem path and %{REQUEST_FILENAME} represents filename with full path for current request.

Your rule has to be written like this:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(wp-content/uploads/[^/]+/test)\.html?$ $1.php [NC,L]

Upvotes: 2

Related Questions