Jeff
Jeff

Reputation: 43

.htaccess authentication w/ friendly url

I'm trying to setup my .htaccess file to enable basic authentication on our development website.

I want the authentication to work on all my site but for certain URL. We are using friendly URL on our site..

I would also like to bypass authentication for certain file types like png, css, etc...

What I have so far looks like this :

SetEnvIfNoCase Request_URI ^/upload/ NO_AUTH
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/.htpasswd
Require valid-user
Satisfy  any
Order deny,allow
Deny from all
Allow from env=NO_AUTH
<FilesMatch "\.(gif|jpe?g|png|css|js|swf)$">
    Satisfy Any
</FilesMatch>

The authentication is working fine, but the SetEnvIfNoCase does not seem to work because I'm still asked for authentication when going to the friendly URL '/upload/'. The FilesMatch part does not seem to work either ..

Anyone can help me with that ?

Thanks !

Upvotes: 3

Views: 212

Answers (1)

Jon Lin
Jon Lin

Reputation: 143926

There's 2 things you need to address.

  1. Your <FilesMatch> container is doing nothing. You already have a Satisfy Any. You should add those extensions to a separate SetEnvIfNoCase

  2. When you are using rewrite rules that rewrite /upload/, you need to include both the "friendly" URI as well as the rewritten URI, because the auth module is applied at every step (obviously, since it's really really bad to allow bypassing of authentication by rewrite/alias). That means, for example, if you have this rule:

    RewriteRule ^upload/(.*)$ /upload_script.php?file=$1 [L]
    

Then you need to have a NO_AUTH line for both /upload/ and /upload_script.php:

SetEnvIfNoCase Request_URI ^/upload/ NO_AUTH
SetEnvIfNoCase Request_URI ^/upload_script.php NO_AUTH

Then to address #1:

SetEnvIfNoCase Request_URI \.(gif|jpe?g|png|css|js|swf)$ NO_AUTH

So an example of the suggestion:

something that you can try is to add a rule (similar to the above RewriteRule example), to route the /upload/ to an intermediate script other than index.php, then from the intermediate script, call index.php.

So using the above example of /upload_script.php you'd add this before any of your rules:

RewriteRule ^upload/ /upload_script.php [L]

So that it looks something like:

RewriteEngine On 

RewriteRule ^upload/ /upload_script.php [L]

RewriteCond %{REQUEST_FILENAME} -s [OR] 
RewriteCond %{REQUEST_FILENAME} -l [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^.*$ - [NC,L] 

RewriteRule ^.*$ index.php [NC,L]

Then, you create a script called upload_script.php which will have something like:

<?php
  include_once "index.php";
?>

You may want to dump the $_SERVER[''] array first to see if everything's set to what Zend's index.php is expecting to see.

Upvotes: 1

Related Questions