Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
What is htmlspecialchars() Function in PHP?
Next article icon

What is .htaccess file in PHP ?

Last Updated : 23 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
What is htmlspecialchars() Function in PHP?
author
code_24x7
Improve
Article Tags :
  • Web Technologies
  • PHP
  • TrueGeek-2021
  • PHP-Questions

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences