Forum Moderators: phranque

Message Too Old, No Replies

.htaccess Rule Based on Filenames

         

HoboTraveler

7:13 pm on Dec 1, 2010 (gmt 0)

10+ Year Member



Hi All,

I need to create a .htaccess rule that would not serve an image if the filename does not have an underscore in it.

Example:

/a/test-foo_test.jpg can be served
/b/bar-foo_image.png can be served
/c/foo-bar.jpg cannot be served

Is it possible to do this with .htaccess rules?

Thanks

g1smd

8:54 am on Dec 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



What should happen to requests without an underscore?

What error should they see?

HoboTraveler

10:04 am on Dec 3, 2010 (gmt 0)

10+ Year Member



The error can be anything. I just do not want them to access filenames without an underscore. The error could be a 404 or a blank page.

Is this possible?

Thanks

g1smd

11:14 am on Dec 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes.

RewriteCond {%REQUEST_FILENAME} !_
RewriteRule \.(png|jpe?g|gif)$ - [F]


For any request for any file ending png, jpg, jpeg or gif, if filename does not include an underscore, send 403 response instead.

Clear browser cache before each test. Use the Live HTTP Headers extension for Firefox to check for the correct HTTP responses.

HoboTraveler

5:36 pm on Dec 3, 2010 (gmt 0)

10+ Year Member



Hello,

I created a .htaccess in the / directory and dumped the rules. I get a 200 OK response, not the 403. Are there any other changes that need to be made? Does the [F] parameter signify the 403?

RewriteEngine On
RewriteCond {%REQUEST_FILENAME} !_
RewriteRule \.(png|jpe?g|gif)$ - [F]

HoboTraveler

5:52 pm on Dec 3, 2010 (gmt 0)

10+ Year Member



This works

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !\_
RewriteRule \.(png|jpe?g|gif)$ - [F]

Thanks for the help!

g1smd

7:06 pm on Dec 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Ah, I wondered if the underscore needed to be escaped, but forgot to mention it or look it up.

I never use underscores in URLs, hence the unfamiliarity.