logo
Apache Lounge
Webmasters

 

About Forum Index Downloads Search Register Log in RSS X


Keep Server Online

If you find the Apache Lounge, the downloads and overall help useful, please express your satisfaction with a donation.

or

Bitcoin

A donation makes a contribution towards the costs, the time and effort that's going in this site and building.

Thank You! Steffen

Your donations will help to keep this site alive and well, and continuing building binaries. Apache Lounge is not sponsored.
Post new topic   Forum Index -> How-to's & Documentation & Tips View previous topic :: View next topic
Reply to topic   Topic: Ultimate htaccess examples tutorial [non-windows]
Author
htaccesselite



Joined: 20 Nov 2006
Posts: 7
Location: Indianapolis, USA

PostPosted: Mon 20 Nov '06 7:40    Post subject: Ultimate htaccess examples tutorial [non-windows] Reply with quote

I have put my security education on the backburner for the last 2 years as I concentrated on learning how web servers work and how to use them. During that time I compiled tons of notes on how to use Apaches htaccess.


Original: htaccessElite's Ultimate htaccess examples

Heres my list of the ultimate htaccess code snippets and examples that I use all the time. I tried to keep them extremely minimalistic.

Each code snippet has been copied from htaccesselite. Additional and detailed info on each htaccess code snippet can be found at htaccessElite

Most of these snippets can be used with a Files or Filesmatch directive to only apply to certain files.





Make any file be a certain filetype (regardless of name or extension)
Code:
#Makes image.gif, blah.html, index.cgi all act as php
ForceType application/x-httpd-php






Authentication Magic

Require password for 1 file:
Code:
<Files login.php>
AuthName "Prompt"
AuthType Basic
AuthUserFile /home/askapache.com/.htpasswd
Require valid-user
</Files>


Protect multiple files:
Code:
<FilesMatch "^(exec|env|doit|phpinfo|w)*$">
AuthName "Development"
AuthUserFile /.htpasswd
AuthType basic
Require valid-user
</FilesMatch>


Example uses of the Allow Directive:
Code:
# A (partial) domain-name
Allow from 10.1.0.0/255.255.0.0

# Full IP address
Allow from 10.1.2.3

# More than 1 full IP address
Allow from 192.168.1.104 192.168.1.205

# Partial IP addresses
# first 1 to 3 bytes of IP, for subnet restriction.
Allow from 10.1
Allow from 10 172.20 192.168.2

# network/netmask pair
Allow from 10.1.0.0/255.255.0.0

# network/nnn CIDR specification
Allow from 10.1.0.0/16

# IPv6 addresses and subnets
Allow from 2001:db8::a00:20ff:fea7:ccea
Allow from 2001:db8::a00:20ff:fea7:ccea/10


Using visitor dependent environment variables:
Code:
SetEnvIf User-Agent ^KnockKnock/2\.0 let_me_in
Order Deny,Allow
Deny from all
Allow from env=let_me_in



Allow from apache.org but deny from foo.apache.org
Code:
Order Allow,Deny
Allow from apache.org
Deny from foo.apache.org


Allow from IP address with no password prompt, and also allow from non-Ip address with password prompt:
Code:
AuthUserFile /home/www/site1-passwd
AuthType Basic
AuthName MySite
Require valid-user
Allow from 172.17.10
Satisfy Any


block access to files during certain hours of the day
Code:
# If the hour is 16 (4 PM) Then deny all access
RewriteCond %{TIME_HOUR} ^16$   
RewriteRule ^.*$ - [F,L]






Redirect non-https requests to https server fixing double-login problem and ensuring that htpasswd authorization can only be entered using HTTPS
Code:
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "google.com"
ErrorDocument 403 [url]https://google.com[/url]






SEO Friendly redirects for bad/old links and moved links
For single moved file
Code:
Redirect 301 /d/file.html [url]http://www.htaccesselite.com/r/file.html[/url]


For multiple files like a blog/this.php?gh
Code:
RedirectMatch 301 /blog(.*) [url]http://www.askapache.com/[/url]$1


different domain name
Code:
Redirect 301 / [url]http://www.newdomain.com[/url]






Require the www
Code:
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ [url]http://www.example.com/[/url]$1 [R=301,L]






Redirect everyone to different site except 1 IP address (useful for web-development)
Code:
ErrorDocument 403 [url]http://www.someothersite.com[/url]
Order deny,allow
Deny from all
Allow from 24.33.65.6






CHMOD your files
chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600
chmod files that you really don't want people to see as 400
NEVER chmod 777, if something requires write access use 766





Variable (mod_env) Magic
Set the Timezone of the server:
Code:
SetEnv TZ America/Indianapolis


Set the Server Administrator Email:
SetEnv SERVER_ADMIN webmaster@htaccesselite.com





Turn off the ServerSignature
Code:
ServerSignature Off






Add a "en" language tag and "text/html; UTF-8" headers without meta tags
Code:
AddDefaultCharset UTF-8
# Or AddType 'text/html; charset=UTF-8' html
DefaultLanguage en-US






Use a custom php.ini

Detailed instructions for doing this whether you are using php as a cgi or the apache module mod_php





Securing directories: Remove the ability to execute scripts

Heres a couple different ways I do it
Code:
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI


This is cool, you are basically categorizing all those files that end in those extensions so that they fall under the jurisdiction of the -ExecCGI command, which also means -FollowSymLinks (and the opposite is also true, +ExecCGI also turns on +FollowSymLinks)





Only allow GET and PUT request methods to your server.

Code:

Options -ExecCGI -Indexes -All
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]






Processing All gif files to be processed through a cgi script
Code:
Action image/gif /cgi-bin/filter.cgi






Process request/file depending on the request method
Code:
Script PUT /cgi-bin/upload.cgi






Force Files to download, not be displayed in browser

Code:
AddType application/octet-stream .avi
AddType application/octet-stream .mpg

Then in your HTML you could just link directly to the file..
Code:
<a href="/movies/mov1.avi">Download Movie1</a>

And then you will get a pop-up box asking whether you want to save the file or open it.





Show the source of dynamic files

If you'd rather have .pl, .py, or .cgi files displayed in the browser as source rather than be executed as scripts, simply create a .htaccess file in the relevant directory with the following:

Code:
RemoveHandler cgi-script .pl .py .cgi






Dramatically Speed up your site by implementing Caching!

Code:
# MONTH
<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>

# WEEK
<FilesMatch "\.(js|css|pdf|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>

# DAY
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>






Prevent Files image/file hotlinking and bandwidth stealing

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^[url]http://[/url](www\.)?askapache.com/.*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ [url]http://www.askapache.com/legal.gif[/url] [R=302,L]






ErrorDocuments

Code:
ErrorDocument 404 /favicon.ico
ErrorDocument 403 [url]https://secure.htaccesselite.com[/url]

Code:
ErrorDocument 404 /cgi-bin/error.php
ErrorDocument 400 /cgi-bin/error.php
ErrorDocument 401 /cgi-bin/error.php
ErrorDocument 403 /cgi-bin/error.php
ErrorDocument 405 /cgi-bin/error.php
ErrorDocument 406 /cgi-bin/error.php
ErrorDocument 409 /cgi-bin/error.php
ErrorDocument 413 /cgi-bin/error.php
ErrorDocument 414 /cgi-bin/error.php
ErrorDocument 500 /cgi-bin/error.php
ErrorDocument 501 /cgi-bin/error.php


Note: You can also do an external link, but don't do an external link to your site or you will cause a loop that will hurt your SEO.
Back to top
htaccesselite



Joined: 20 Nov 2006
Posts: 7
Location: Indianapolis, USA

PostPosted: Tue 05 Dec '06 6:46    Post subject: Reply with quote

There is an updated version of the Ultimate htaccess examples tutorial

and a really good example .htaccess file


Last edited by htaccesselite on Sat 31 Mar '07 8:45; edited 1 time in total
Back to top
James Blond
Moderator


Joined: 19 Jan 2006
Posts: 7288
Location: Germany, Next to Hamburg

PostPosted: Tue 27 Feb '07 21:25    Post subject: Reply with quote

Now there is a great example on the official wiki

http://wiki.apache.org/general/htaccess
Back to top
htaccesselite



Joined: 20 Nov 2006
Posts: 7
Location: Indianapolis, USA

PostPosted: Wed 14 Mar '07 21:31    Post subject: Reply with quote

James Blond.. the wiki article was taken down..


Heres the full list of the ultimate htaccess article.

For Webmasters

When site is Under Construction
Redirect everyone to different site except 1 IP
Redirect everyone to different site except 1 IP
Redirect Everyone but you to alternate page on your server.
Set the Timezone of the server
Set the Server Administrator Email
Turn off the ServerSignature
Force Files to download, do not display in browser
Process All .gif files with a cgi script
Process Requests with certain Request Methods
Make any file be a certain filetype
Use IfModule directive for robust code

Custom HTTP Headers

Prevent Caching 100%
Remove IE imagetoolbar without meta tag
Add Privacy (P3P) Header to your site
Add a en-us language header and urf-8 without meta tags!

Using AddType
Using the Files Directive
Using the FilesMatch Directive


PHP htaccess tips

When php run as CGI
Use a custom php.ini with mod_php or php as a cgi

When php run as Apache Module (mod_php)
When cgi php is run with wrapper (FastCGI)


SEO Search Engine Friendly Redirects without mod_rewrite

For single moved file
Redirect Home to new Domain
For multiple files like a blog/this.php?gh
Redirect Entire site to single file

mod_rewrite tips and tricks

Mostly .htaccess rewrite examples should begin with:
Check for a key in QUERY_STRING
Removes the QUERY_STRING from the URL
Fix for infinite loops
Require the www
Require no www
Redirect .php files to .html files (SEO friendly)
Redirect .html files to actual .php files (SEO friendly)
block access to files during certain hours of the day
Rewrite underscores to hyphens for SEO URL
Require the www without hardcoding
Require no subdomain
Require no subdomain
Redirecting Wordpress Feeds to Feedburner
Only allow GET and PUT request methods
Prevent Files image/file hotlinking and bandwidth stealing
Stop browser prefetching
Make a prefetching hint for Firefox.

Speed up your site with Caching and cache-control

htaccess time cheatsheet
Caching with both mod_expires + mod_headers
Caching with mod_headers
Caching with mod_expires

Apache Authentication in htaccess

Require password for 1 file only
Protect multiple files:
Using the Apache Allow Directive in htaccess

network/netmask pair
IP address
More than 1 IP address
Partial IP addresses, first 1 to 3 bytes of IP, for subnet restriction
network/nnn CIDR specification
IPv6 addresses and subnets
Deny subdomains
Allow from IP without password prompt, and also allow from any address with password prompt
Skeleton .htaccess file to start with


Security with Apache htaccess

CHMOD your files
Prevent access to .htaccess and .htpasswd files
Show Source Code instead of executing
Securing directories: Remove the ability to execute scripts
ErrorDocuments

Common STATUS Codes and ErrorDocument Implementations
When using CGI PHP, php 404 Error example
An example 404 Error page in perl cgi
ErrorDocuments generated by Apache


SSL example usage in htaccess

Redirect non-https requests to https server
Rewrite non-https to HTTPS without mod_ssl!

Based on HTTPS variable (best)
Based on SERVER_PORT
Redirect everything served on port 80 to HTTPS URI
Redirect particular URLs to a secure version in an SSL SEO method
Check to see whether the HTTPS environment variable is set
Rewrite to SSL or NON-SSL using relative URL!


Apache Variable fun (mod_env)

Using visitor dependent environment variables:
Special Purpose Environment Variables
SetEnvIf

SetEnvIfNoCase Example
SetEnvIfNoCase Example 2
Back to top


Reply to topic   Topic: Ultimate htaccess examples tutorial [non-windows] View previous topic :: View next topic
Post new topic   Forum Index -> How-to's & Documentation & Tips