seekairun
seekairun

Reputation: 13

.htaccess How to check if URI + file extension doesn't exists before RewriteRule

When a page is accessed via an URL like this:

/pagename

How can we check if the following file exists via htaccess

/pagename.htm

And then load index.php if not?

Here's what I'm working with:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

I've tried a variation of this but no luck: RewriteCond %{REQUEST_URI} !/.htm -f

Upvotes: 1

Views: 2864

Answers (1)

dambrisco
dambrisco

Reputation: 865

# If the URI is not .htm and doesn't have any additonal params, try .htm
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?![^/]+\.htm)([^/]+)$ $1.htm [L,R=302]
# Adding the R flag causes the URI to be rewritten in the browser rather than just internally

# If the URI is .htm but it doesn't exist, pass to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/\.]+\.htm)$ $1/no [L]

# Passes requested path as 'q' to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/no/?$ index.php?q=$1 [L]

Should work rather elegantly for you. If it can't find the file, it just passes it on to index.php. You can of course modify what variable it uses, I just used 'q' for generic purposes.

Also, do note that you can condense this down to a single set of RewriteConds. I've expanded them for annotation purposes here.

Upvotes: 5

Related Questions