How to create htaccess file Updated complete guide 2022

by Manu
how to create htaccess file Updated complete guide 2022

In this guide we are going to see htaccess redirects, authentication, removing file extension from url handling custom urls and more so let’s get started.

We will be using xampp for our testing so install xampp in your system from here.

Also if you want to check documentation for .htaccess then you can visit here for official documentations.

Ok Once you have local server up and running then we proceed.

.Htaccess file

.htaccess file is server direcive file, Where we define how we want things to go in that particular directory.

.Htaccess redirect example

So when we have xampp server running we can visit an url to see if all is set so visit “localhost”. It will redirect you to “localhost/dashboard”.

Now we can customize this redirect so lets say we have an application which has a file “index.php”. which shows “Hello” text to user.

So this application is in htdocs folder. lets call this application test so it will be in “htdocs/test” folder. ok so we can access it using url “localhost/test”.

Now we want is when we go to localhost it will redirect to localhost/test, However currently it is redirecting to localhost/dashboard.

So first go to “xampp/htdocs” folder and open index.php. This file is redirecting to “localhost/dashboard”. we can stop this redirecting by removing or commenting the code.

<?php
   if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
      $uri = 'https://';
   } else {
      $uri = 'http://';
   }
   $uri .= $_SERVER['HTTP_HOST'];
   header('Location: '.$uri.'/dashboard/');    // Here it is redirecting so comment or remove this line
   exit;                                       // also remove or comment this line too
?>
Something is wrong with the XAMPP installation :-(

So it should be like this

<?php
   if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
      $uri = 'https://';
   } else {
      $uri = 'http://';
   }
?>
Something is wrong with the XAMPP installation :-(

Now you will see “Something is wrong with the XAMPP installation :-(” text on the page. Let’s add our redirect now which will redirect to “localhost/sky”.

So inside “xampp/htdocs” folder create a file “.htaccess” and add this code.

htaccess Redirect to Subfolder

RewriteEngine On
RewriteRule ^$ /sky [L]

There you see it works.

Authentication in htaccess file

For Authentication you can add this code

RewriteEngine On
AuthName "Restricted Content"
AuthType Basic
AuthUserFile .htpasswd
Require valid-user

For AuthUserFile you will need to get Root path, you can use

echo $_SERVER['DOCUMENT_ROOT']; // To check the Document root path

Here basically we are sing that ask for user name and password. if authenticated then proceed. otherwise not.

Ok we in line

AuthUserFile .htpasswd

We are sing user name and password should match what we have in file “.htpasswd”. which is in the same directory

// .htpasswd file has below gien username and password

john:$apr1$jpnymgh2$wnxzM01O9Qk5yPubimHPo.

You can have any username or password here just to show you what process looks like we added user as john.

Here we need to authenticate. Before accessing the page. Password in encrypted you can get your password encrypted from google just search for “htpasswd generator”.

If you face problem anywhere check apache error logs. It is in “htdocs/logs” directory

Using Cache in htaccess

For caching images you can use this code

<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
	Header set Cache-Control "max-age=86400, public"
</Filesmatch>

So i added one image in page and refreshed it next time when i refreshed, then image loaded from cache. Have a look

It also shows when cache will expire which is “1day”.

Removing file extension using .htaccess

For this we need to add this code

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

See Here we say “$1.php” where we are saying accept without .php so we can now load page without .php extension.

See all works

Handle custom url using htaccess

Ok now we need to do this, So for example if we have api in url then we need to load some certain file. so here how we can achieve this

add this line in .htaccess

RewriteEngine On
RewriteRule ^api index.php

So we are saying if there has “api” word in url then show index.php

How to Set a Custom 404 Page With .htaccess

Lets configure error pages for 404 page we create a folder “errors” and then we create files inside it for example. “404_error.php”.

RewriteEngine On
ErrorDocument 404 /sky/errors/404_error.php // Remember path should be from document root

Now add any text in 404_error.php that will display on web page.

We can add more pages for other error codes just the same way.

Redirect to index.php instead going to error pages .htaccess

RewriteEngine On


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d


RewriteRule . /sky/index.php // our app folder is called sky so sky/index.php we redirected to.

You may also like

Leave a Comment