This page looks best with JavaScript enabled

15 htaccess tips and tricks

 ·   ·  β˜• 7 min read

    15 useful htaccess tips and tricks

    In this article, I am going to discuss htaccess tips and tricks. I am talking about URL rewriting tips, htaccess SEO optimization, .htaccess security tips, .htaccess deny access to directory, .htaccess deny directory listing etc. .htaccess is most important for a website. before starting .htaccess tips and tricks we should know about .htaccess first.

    what is .htaccess?

    .htaccess is a server configuration file which is use for Apache Web Server software. when a .htaccess place in a web directory then this .htaccess file loaded via Apache Web Server and follow .htaccess instructions. Apache web server works which command use on .htaccess file. .htaccess files provide a way to change web server configurations.
    How to create a .htaccess file?

    If you want to customize your website and change configurations of your website using .htaccess then you should create .htaccess file first. login into your control panel and create a new file name as .htaccess. If you want to create a .htaccess file from your PC then follow this steps-

    1. Create a new text file,
      Press right click > New > Text Document

    2. Open this file in notepad editor

    3. Save file name as .htaccess,
      file > Save As > File name “.htaccess” > Save
      .htaccess file created successfully.

    how to create htaccess file
    Or .htaccess file is now ready we are in the way of various .htaccess tricks and tips.

    Custom Directory Index Files

    DirectoryIndex index.php index.html index.htm
    You can change your directory index and set custom directort index file using this htaccess code. If you use DirectoryIndex index.php code in .htaccess file then server run index.php file as default web page. You can set your custom file as you want.

    Prevent Directory Listing

    You can deny users to directory browsing, users couldn’t browse directories if you prevent via .htaccess
    Options -Indexes
    Force www or non-www

    You can specify your website www or non-www by using .htaccess www and non-www means when a user browse your website then which type of link will display in users browser.
    www.example.com or example.com selct is yours. You can specify it using .htaccess

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

    Custom Error Page

    You can setup custom error pages for your website. If you not set custom error pages for your website then your website will display default error pages which are provided by your hosting service provider. but you can set custom error pages using a .htaccess file.

    ErrorDocument 400 error/400-badrequest.php
    ErrorDocument 401 error/401-authorizationrequired.php
    ErrorDocument 404 error/404-notfound.php
    ErrorDocument 403 error/403-forbidden.php
    ErrorDocument 500 error/500-servererror.php
    

    Redirect browser HTTP to HTTPS (SSL)

    You can redirect your website url http to https using .htaccess . If you use SSL (secure socket layer) and if you want to redirect all pages with https then you can use this via .htaccess code snippet

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    

    Rewrite URLs using htacccess

    An SEO friendly URL is most important to improve in a search engine. Search engine prefers SEO friendly URL. If you want to rewrite and make SEO friendly URL then you can make it easily via .htaccess. Follow this code snippet and make your website SEO Friendly.

    RewriteEngine on
    RewriteRule ^user/([A-Za-z0-9-_+]+)/?$ user.php?name=$1 [NC,L]
    

    Make a profile page www.example.com/user.php?name=username to www.example.com/user/username

    RewriteEngine on
    RewriteRule ^user/([a-zA-Z0-9_-]+)/([0-9]+)$ user.php?id=$2
    

    This code snippet will work like www.example.com/user/profile/username

    .htaccess hide file extension

    If you want to hide file extension from your website then you can do it using .htaccess follow this code snippet and hide file extensions.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^.]+)$ $1.php [NC,L]
    if you use this snippet in your website’s .htaccess file then you can browse your websites php files without using php extensions
    www.example.com/about-us.php to www.example.com/about-us

    Compress Files Using .htaccess

    optimize your website loading time by compressing files, use this snippet and compress files of your website and make your website faster.

    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    

    File Protection using .htaccess

    You can protect important files using .htaccess use this code snippet and protect files

    <Files php.ini>
    Order Allow,Deny
    Deny from all
    </Files>
    <Files .htaccess>
    Order Allow,Deny
    Deny from all
    </Files>
    

    htaccess header set cache-control

    When a user browses your website then all of your website data like CSS, Scripts , Images are downloaded as browser cache. When this user will return your website then these data will reload from users browser cache. use this code snippet,

    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresDefault "access 1 month"
    </IfModule>
    <ifModule mod_headers.c>
    <filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
    Header set Cache-Control "max-age=2592000, public"
    </filesMatch>
    <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "private, must-revalidate"
    </filesMatch>
    </ifModule>
    

    Secure website using .htaccess

    You can secure your website using a .htaccess file. You can prevent XSS, SQL injection using a .htaccess file. Use this code snippet and make your website secure,
    Options +FollowSymlinks
    ServerSignature Off

    Rule #4a - Block out any script trying to base64_encode crap to send via URL
    RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]

    Rule #4b - Block out any script that includes a <script> tag in URL
    RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]

    Rule #4c - Block out any script trying to set a PHP GLOBALS variable via URL
    RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]

    Rule #4d - Block out any script trying to modify a _REQUEST variable via URL
    RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})

    Rule #4e - Send all blocked request to homepage with 403 Forbidden error!
    RewriteRule ^(.*)$ index.php [F,L]
    Prevent XSS attacks using .htaccess

    If you want to prevent Cross Site Scripting (XSS) you can do it suing .htaccess now it’s time to make your website more secure, let’s see how to protect XSS using .htaceess,

    RewriteCond %{QUERY_STRING} http://([a-zA-Z0-9_\-]*) [NC,OR]
    RewriteCond %{QUERY_STRING} http:/([a-zA-Z0-9_\-]*) [NC,OR]
    RewriteCond %{QUERY_STRING} cmd= [NC,OR]
    RewriteCond %{QUERY_STRING} &cmd [NC,OR]
    RewriteCond %{QUERY_STRING} exec [NC,OR]
    RewriteCond %{QUERY_STRING} execu [NC,OR]
    RewriteCond %{QUERY_STRING} concat [NC]
    RewriteCond %{REQUEST_METHOD} ^(HEAD|TRACE|DELETE|TRACK) [NC,OR]
    RewriteCond %{THE_REQUEST} ^.*(\
    |\
    |%0A|%0D).* [NC,OR]
    RewriteCond %{HTTP_REFERER} ^(.*)(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
    RewriteCond %{HTTP_COOKIE} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
    RewriteCond %{REQUEST_URI} ^/(,|;|:|<|>|">|"<|/|\\\.\.\\).{0,9999}.* [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|scan).* [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
    RewriteCond %{QUERY_STRING} ^.*(;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark|print|printf|system|exec|scanf).* [NC,OR]
    RewriteCond %{QUERY_STRING} ^.*(localhost|loopback|127\.0\.0\.1).* [NC,OR]
    RewriteCond %{QUERY_STRING} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC]
    RewriteRule ^.* - [F]
    

    Prevent SQL injections using htaccess

    SQl Injection is a code base injection. Hackers using SQL Injection to dump information from a database. For prevent SQL Injection use this code snippet in your website .htaccess,

    RewriteCond %{QUERY_STRING} UNION([%20\ /\*+]*)ALL([%20\ /\*+]*)SELECT [NC,OR]
    RewriteCond %{QUERY_STRING} UNION([%20\ /\*+]*)SELECT [NC,OR]
    RewriteCond %{QUERY_STRING} /\* [NC,OR]
    RewriteCond %{QUERY_STRING} \*/ [NC]
    RewriteRule ^.* - [F]
    RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
    RewriteCond %{QUERY_STRING} http:.*\/.*\/ [OR]
    RewriteCond %{QUERY_STRING} ..*\/ [OR]
    RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
    RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
    RewriteCond %{QUERY_STRING} [^a-z](declare|char|set|cast|convert|delete|drop|exec|insert|meta|script|select|truncate|update)[^a-z] [NC]
    RewriteRule (.*) - [F]
    

    Block Bad IP Using .htaccess

    You can block IP Address using .htaccess file. You can block spammy IP address by this, Just add this code snippet in your .htaccess file.

    Order Deny,Allow
    Deny from 127.0.0.1
    Deny from 127.0.0.2
    

    If you want to block some specific IP addresses from your website then add this snippet and write the targeted IP address which you want to block.

    Lock Admin Page Using htaccess

    If you want to access admin page or admin login page from a specific IP address then you can do it by using .htaccess. Protect important pages and allow some pages from a fixed IP. Improve your website more secured

    <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
    RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$
    RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
    RewriteRule ^(.*)$ - [R=403,L]
    </IfModule>
    

    You can change this IP address and write your own IP address. When you browse wp-login.php and wp-admin pages from your IP which is defined in .htaccess then server permit you to access these pages otherwise, it will show forbidden error. So, you can make your website’s important pages more secured.


    Ohidur Rahman Bappy
    WRITTEN BY
    Ohidur Rahman Bappy
    πŸ“šLearner 🐍 Developer