htaccess

PHP SECURITY 2021 Web performance and loading speed are among the hottest topics in the web. If your site or blog is slow, chances are people won’t ever come back. The good news is that some of the most important site optimizations can be achieved by means of .htaccess tricks. In this blog post we provide a useful .htaccess snippets collection with the help of which you’ll be able to redirect URLs, prevent hotlinking, enhance site speed, among many other things.

.htaccess is a special configuration file that provides multiple commands for controlling and configuring the Apache Web Server. However, by no means all web developers know and understand it fully. The true power of .htaccess snippets often goes unnoticed. These can be utilized not only for speeding up your site, but also for SEO optimization and a number of other purposes.

1. SEO-friendly URLs

Websites with clear URL structure rank higher than those with addresses like ‘index.php?product_id=’. Ideally, a SEO-friendly URL should feature a keyword and duplicate some content from your blog post title or the name of the page, which guarantees it will be properly indexed by Google or other search engines.

ForceType application/x-httpd-php5

2.Redirect form your old domain to the new one

The technique is better known as 301 redirect. With its help you can redirect both separate pages and the entire sites. To redirect a single page, use code:

Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html

3.For the entire site:

Redirect 301 / http://newsite.com/

In both cases, the old URL comes first, with the address of the new domain following it in the second part of code.

Remove www from URL

For the users’ convenience or for better SEO ranking, you might want to remove www from the URL of your site. With the help of the following code you’ll be able to remove www and forward the users to your site address starting with http:/ ….

RewriteEngine On
RewriteCond %{HTTP_HOST} !^mysite.com$ [NC]
RewriteRule ^(.*)$ http://mysite.com/$1 [L,R=301]

4.Error Pages: None of your visitors should see a blank page when they end up on a broken URL. Instead, create a beautifully-designed and informative error page that would provide the visitors with working links to keep on browsing your site.

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authrequest.html
ErrorDocument 403 /errors/forbidden.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/servererror.html

5.Better site speed with better caching: The faster your page loads, the higher your site will rank in search results. Web developers make a struggle to create websites that would smoothly run on both desktop and mobile devices, and not make them wait for long till the site loads. That’s when caching comes in handy. However, at this point there is one important thing to consider – you should make sure there are no other caching systems in place. Additionally, you need to decide on caching length. In the example below you can see how to set files to cache for 24 hours.


Header set Cache-Control "max-age=28800"

6.Block access to backup and source files: Some file may go under risk and pose a great security danger when someone has access to them. For it not to happen, apply the following code.


## Apache 2.2
Order allow,deny
Deny from all
Satisfy All

## Apache 2.4
# Require all denied

7.Password protect a directory: Protecting documents, images and other data from unauthorized users is of high value. Of course, you can accomplish this by means of PHP to ask users for login authorization information, however the same can be done much easier and effectively with .htaccess. You will need to prepare two files – the first one is the .htaccess file with code and another one is .htpasswd file with usernames and passwords off all the allowed users. Here is how the .htaccess file looks like.

AuthType Basic
AuthName "restricted area"
AuthUserFile /home/davidwalsh/html/protect-me-dir/.htpasswd
require valid-user

8.Gzip compression:Compression of HTML and CSS files is quite popular now as it provides for faster page loading. If for some reason you still don’t compress files on your site, it’s high time to start practicing it. Add this code to the .htaccess file on your server.


mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

9.Ban someone from your site: If you don’t want particular users or some malicious parties to have access to your site content, then you can easily ban them from your website with the help of the following code:


order allow,deny
deny from 123.456.78.9
deny from 987.654.32.1
allow from all

10. Add HTTP To HTTPS Secure Website: At this point if you go to https://yoursite.com you should see it load! Congrats, you’ve successfully installed SSL and enabled the HTTPS protocol! But your visitors aren’t protected just yet, you need to make sure they’re accessing your site through HTTPS!Keep in mind that you typically only need to protect a few pages, such as your login or cart checkout. If you enable HTTPS on pages where the user isn’t submitting sensitive data on there, it’s just wasting encryption processing and slowing down the experience. Identify the target pages and perform one of the two methods below. You can update all links to the target pages to use the HTTPS links. In other words, if there’s a link to your cart on your home page, update that link to use the secure link. Do this for all links on all pages pointing to the sensitive URLs.However, if you want to ensure that people can only use specific pages securely no matter what links they come from, it’s best to use a server-side approach to redirect the user if it’s not HTTPS. You can do that with a code snippet inserted on top of your secure page. Here’s one in PHP:

  • Redirect All Web Traffic: If you have existing code in your .htaccess, add the following:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
  • Redirect Only a Specific Domain: For redirecting a specific domain to use HTTPS, add the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
  • Redirect Only a Specific Folder: Redirecting to HTTPS on a specific folder, add the following:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.yourdomain.com/folder/$1 [R,L]

file?

.htaccess is a file used by Apache web server to set server environment variables and configuration settings for the specified directory only. It is usually found in your website root directory, e.g. /home/username/public_html/.htaccess

 

1. Enable HTTP Strict Transport Security (HSTS) in .htaccess

HTTP Strict Transport Security (HSTS) support is often flagged up by SEO and security scanners. What does it do? It simply tells web browsers that you want your website to only be accessed over a valid https connection. To enable it just add this line to htaccess:

Header set Strict-Transport-Security "max-age=31536000" env=HTTPS

 

2. Block PHP code execution in specified directories in .htaccess

This is a quick .htaccess website security tweak that works for WordPress or any other custom website that has directories you want to protect from PHP code execution. Using this .htaccess trick you can easily block PHP execution in your core WordPress directories to stop common attacks, but check your website carefully in case it breaks existing theme or plugin functionality. For finer control, we recommend the Sucuri WordPress security plugin which enables you to whitelist specific files while blocking the rest. To implement this just create a .htaccess file in each of the directories that you want to protect and add this code:

<FilesMatch ".(?i:php)$">
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
</FilesMatch>  

 

3. Limit access by IP address in .htaccess

If you have a static IP address then you can use this to control access to specific files or directories on your website such as your login page or admin area. This is often used to secure WordPress websites by restricting the wp-login.php and /wp-admin/ directory, but works equally well for other content management systems and custom websites and apps.

To limit access to a specific file:

<Files <YOUR FILENAME>.php>
Order deny,allow
Deny from all
Allow from <YOUR IP ADDRESS>
</Files>

To limit access to a whole directory, create a .htaccess file in the directory you want to protect, and add this code:

Order Deny,Allow
Deny from all
Allow from <YOUR IP ADDRESS>

 

4. Prevent directory browsing in .htaccess

This one is often set by default by your hosting provider, but if not then you can add the following line to your .htaccess file to prevent browsing of your directories via a web browser.

Options All -Indexes

 

5. Prevent image hotlinking in .htaccess

This stops other websites displaying images hosted on your website. This isn’t a huge issue but if the culprit has a lot of traffic it can quickly use up your bandwidth and cause your website to be suspended or incur extra bandwidth costs. You can also replace the image with one that shows your website name and address to give yourself a bit of promotion, or replace it with something a bit cheeky as you see fit. Just add this code to your .htaccess file and change yourdomain and your no hotlinking image URL as appropriate:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com/.*$ [NC]
RewriteRule .(jpeg|JPEG|jpe|JPE|jpg|JPG|gif|GIF|png|PNG)$ https://www.yourdomain.com/no-hotlinking.png [R,L]

 

6. Header for Cross-Origin Resource Sharing (CORS)

This was flagged by a recent website security scan on a client website. Basically this header limits access to resources like CSS stylesheets, images, and scripts to only the specified domain. We suggest reading more about CORS on the Mozilla Developers website, and then if you want to enable this just add the following line to .htaccess:

Header set Access-Control-Allow-Origin https://www.yourdomain.com

 

7. Disable HTTP Track & Trace

Another one often flagged up by security scans is to disable HTTP TRACE and HTTP TRACK methods. This can be done in Apache either by adding TraceEnable Off to your httpd.conf or by adding the following code to your .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]

 

<

p>