What is .htaccess file in PHP ?
Last Updated : 23 Nov, 2021
The .htaccess (Hypertext Access) file is an Apache distributed server configuration file. You can use the .htaccess file to set server configurations for a specific directory. This directory can be the root directory of your website or another subdirectory where the .htaccess file is created in order to enable extra features for that subdirectory.
You can use the .htaccess file to modify various configurations and thus make changes to your website. These changes include authorization, error handling, redirects for specific URLs, user permissions, etc. Like any other Apache configuration file, the .htaccess file is read from top to bottom. That is, the above configurations are performed before those below.
Common uses of the .htaccess file:
1. Change the default start page: Suppose you want to change your home page (e.g. index.html) with some other HTML page (e.g. home.html) while keeping the index.html file intact, you can change the default landing page by adding the code below in your .htaccess file.
DirectoryIndex home.html
In the configuration file, it is also possible to add more than one file. Here in this example, first, the server will check for index.html, if it does not find a file with that name, it continues to home.htm and so on.
DirectoryIndex index.html home.html config.php
2. Block a specific IP or range of IPs: You can also block a specific IP address or a range of IP addresses from visiting your website. To do this, you need to add these lines to your .htaccess file:
Denying specific IP: By using this template you can block any desired IP address
Order Deny,Allow Deny from 192.206.221.140 (Here 192.206.221.140 is a specific IPv4 Address)
Denying list of IPs: By listing IP addresses line by line you can block a set of IP addresses.
Order Deny,Allow Deny from 185.120.120.120 Deny from 192.190.190.190
Denying access from a specific domain: Suppose you want to deny access to your hosted website from a particular domain (e.g., www.redirectingdomain.com) which contains a link to your website, in that case, you can use the code below in your .htaccess file. This will show 403 Forbidden error on clicking the link to your website from redirectingdomain.com
SetEnvIfNoCase Referer "redirectingdomain.com" bad_referer Order Allow,Deny Allow from ALL Deny from env=bad_referer
Block or allow ranges of IP addresses :
Order Allow,Deny Deny from 192.192.*.* Allow from all
Where * is used for whole octets
Note: To restrict access from certain countries, you must obtain the IP address ranges assigned to that particular country. It is important to note that this method is not 100% efficient as the IP address assignments may change and the IP address ranges may overlap. Even so, this method blocks most of the traffic from the specified countries.
3. 301 Permanent Redirect: 301 is an HTTP response code to your web browser from the webserver. A 301 status code indicates that the requested resources have been permanently moved to a new URL. 301 redirects are very useful when a page is no longer relevant or the page is deleted. You can use the below code to apply 301 redirects.
RewriteEngine on RewriteCond %{HTTP_HOST} ^domain1.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.domain1.com [NC] RewriteRule ^(.*)$ http://domain2.com/$1 [L,R=301,NC]
Or you can simply use the code below
Redirect 301 / http://domain.com
4. WWW to non-WWW and non-WWW to WWW: As search engines consider "www" and "non-www" URLs two different things, so redirecting requests from non-preferred domains becomes very important. Let's take an example of "www.example.com"
To make the 301 redirects from www to non-www you have to add the following code into your .htaccess file:
RewriteEngine on RewriteCond %{HTTP_HOST} ^geeksforgeeks.com [NC] RewriteRule ^(.*)$ http://www.geeksforgeeks.com/$1 [L,R=301,NC]
If you want to make 301 redirects from non-www to www domain add the following code:
RewriteEngine on RewriteCond %{HTTP_HOST} ^www.geeksforgeeks.com [NC] RewriteRule ^(.*)$ http://geeksforgeeks.com/$1 [L,R=301,NC]
5. Redirect from HTTP to HTTPS:
Why redirect traffic from HTTP to HTTPS?
There are two main reasons, one is Security because it ensures that the user data is encrypted from the user browser to the webserver and the second reason is the SEO(Search Engine Optimization) because HTTPS websites have higher advantages of ranking over HTTP websites. If you want to transfer the entire traffic of your website from HTTP to HTTPS, that you will need to add the following to your .htaccess file.
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] Header always set Content-Security-Policy "upgrade-insecure-requests;" <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>
6. Customize your Error Page: If you want to customize your 404 error page, you can define your own custom error page in the .htaccess file. Just copy the below text in your .htaccess file.
# Example 1: redirect errors to html files ErrorDocument 404 /404.html # Example 2: redirect errors to PHP file ErrorDocument 404 /error.php?q=404
7. Authenticated folder: For authentication purposes, you can protect a directory of an application by adding the code given below in your .htaccess file. Once the .htaccess file is updated your directory will require a username and password to access it.
AuthName "Your Authenticated Folder" AuthUserFile /path/.htpasswd AuthType Basic require valid-user
Here the first line of the code tells the Apache webserver that the name of the password-protected directory is “Your Authenticated Folder”. Second-line tells the path of that folder and the next line determines the type of authentication, in this example, we are using HTTP Basic authentication. Finally, the last line says we need valid credentials.
Similar Reads
What is htmlspecialchars() Function in PHP?
The htmlspecialchars() function in PHP is used to convert special characters to HTML entities. This is particularly useful for preventing XSS (Cross-site Scripting) attacks by ensuring that any special characters in user input are not interpreted as HTML by the browser. For example, characters like
2 min read
What is autoloading classes in PHP ?
In order to use a class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature does not need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registe
2 min read
How to parse HTML file in PHP ?
In this article, we will learn to parse HTML in PHP. What is parsing? Generally parsing is converting one data type to another. It means how we can convert various data types to HTML. For example: Converting string to HTML. Why do we need parsing? To add the dynamic data (HTML content) at a certain
2 min read
PHP is_file( ) Function
The is_file() function in PHP is an inbuilt function which is used to check whether the specified file is a regular file or not. The name of the file is sent as a parameter to the is_file() function and it returns True if the file is a regular file else it returns False. Syntax: bool is_file($file)
2 min read
What is .tpl file in PHP web design?
TPL is a template file which is a common text file that contains user-defined variables that are entitled to be overridden by user-defined output content when a PHP web application parses the template file. These are used by web applications with server script PHP(but not restricted to) as a templat
4 min read
How to write Into a File in PHP ?
In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file
2 min read
What is the purpose of php.ini file ?
In this article, we will learn about the purpose of the php.ini file. At the time of PHP installation, php.ini was a special file provided as a default configuration file. Purpose of php.ini file:Itâs a very essential configuration file that controls what a user can or cannot do with the website.Eac
5 min read
PHP | is_uploaded_file( ) Function
The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST. This function can b
2 min read
What is the use of $GLOBALS in PHP ?
In this article, we will discuss $GLOBALS in PHP. $GLOBALS is a superglobal variable used to access global variables from anywhere in the PHP program. PHP stores all global variables in an array called $GLOBALS[index]. Syntax: $GLOBALS['index']=value;value is the input value.The index is the unique
1 min read
PHP File Handling
File handling allows the developers to interact with the serverâs file system, which is essential for tasks like saving data, processing user-uploaded files, and generating dynamic content. PHP File Handling enables developers to read from and write to files, making it a core feature for web applica
5 min read