Search code examples
.htaccessmod-rewriteip

How to block access to a website except a repertory?


I'm trying to block all access to my website with .htaccess except for my IP.

Problem is I got some images in /img/ that I use for my address e-mail signatures, so I need these to be free.

Thanks.

At first I had this :

RewriteCond %{REMOTE_ADDR} !^38\.37\.31\.238$
RewriteCond %{REQUEST_URI} !^/maintenance.php$
RewriteCond %{REQUEST_URI} !^/signature/link-icon.png
RewriteCond %{REQUEST_URI} !^/signature/mail-icon.png
RewriteCond %{REQUEST_URI} !^/signature/profil-picture.png
RewriteCond %{REQUEST_URI} !^/signature/profil.png
RewriteCond %{REQUEST_URI} !^/signature/skype-icon.png
RewriteCond %{REQUEST_URI} !^/signature/tel-icon.png
RewriteRule .* /maintenance.php [L,R=302]

But I don't want to redirect to maintenance.php no more, just a random 404 error or something like this. I just wanna use the domain for the e-mails.


Solution

  • It would perhaps be more logical to return a 403 Forbidden, rather than a 404, unless you have specific requirements?

    :
    RewriteRule .* /maintenance.php [L,R=302]
    

    To send a 403 you basically just need to change the last line to:

    RewriteRule ^ - [F]
    

    Or change the flags (3rd) argument to [R=404] to send a 404 instead. No need for the L flag here.

    Although I would tend to split this into two rules...

    # Public URLs
    # (Assuming all public URLs are in the "/signature" subdirectory)
    RewriteCond %{REQUEST_URI} link-icon\.png$ [OR]
    RewriteCond %{REQUEST_URI} mail-icon\.png$ [OR]
    RewriteCond %{REQUEST_URI} profil-picture\.png$ [OR]
    RewriteCond %{REQUEST_URI} profil\.png$ [OR]
    RewriteCond %{REQUEST_URI} skype-icon\.png$ [OR]
    RewriteCond %{REQUEST_URI} tel-icon\.png$
    RewriteRule ^signature/ - [L]
    
    # Block the reset, except for the specific IP address
    RewriteCond %{REMOTE_ADDR} !=203.0.113.111
    RewriteRule ^ - [F]
    

    Note that the = preifx in the last rule makes it an exact string match, not a regex.