Search code examples
wordpress.htaccessmod-rewritebasic-authentication

.htaccess, mod_rewrite, and basic authentication


I am working on a Wordpress site, and my pages are using a permalink structure that mod_rewrites them to look like directories. For a few pages I want to use Basic Authentication to password protect a few of the pages. How would I write this in my .htaccess file? Am I protecting the file, or the rewritten address?


Solution

  • You won't need mod_rewrite for this, hopefully, this should do the trick:

    SetEnvIfNoCase Request_URI ^/some/path/to/protect require_auth=true
    SetEnvIfNoCase Request_URI ^/another/protected/path require_auth=true
    
    # Auth stuff
    AuthUserFile /var/www/htpasswd
    AuthName "Password Protected"
    AuthType Basic
    
    # Setup a deny/allow
    Order Deny,Allow
    # Deny from everyone
    Deny from all
    # except if either of these are satisfied
    Satisfy any
    # 1. a valid authenticated user
    Require valid-user
    # or 2. the "require_auth" var is NOT set
    Allow from env=!require_auth
    

    The mod_auth and mod_env modules should have precidence over mod_rewrite, so your fake directory structure should stay the same. You'd just need to fill out a SetEnvIfNoCase Request_URI ^/some/path/to/protect require_auth=true for each one, then fill out the rest of the auth stuff to suit your needs.