How To Set Up mod_rewrite for Apache on Ubuntu 18.04

Prerequisites:-

Make user Apache 2 installed on your server – How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04.

Step 1 — Installing Apache

Step 2 — Enabling mod_rewrite

Step 3 — Setting Up .htaccess

In this section, we will setup a .htaccess file for simpler rewrite rule management. A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web application’s security. The period that precedes the filename ensures that the file is hidden. We will need to set up and secure a few more settings before we can begin. First, allow changes in the .htaccess file. Open the default Apache configuration file using nano or your favorite text editor.

Inside that file, you will find the block on line 1. Inside of that block, add the following block:

Now, create the .htaccess file.

Add this first line at the top of the new file to activate the RewriteEngine.

Save and exit the file. To ensure that other users may only read your .htaccess, run the following command to update permissions.

Step 4 — Setting Up Files

In this section, we will set up a basic URL rewrite, which converts pretty URLs into actual paths to code. Specifically, we will allow users to access example.com/about. We will begin by creating a file named about.html.

Copy the following code into the HTML page.

You may access your web application at your_server_ip/about.html or example.com/about.html. Now notice that only about.html is accessible; if you try to access your_server_ip/about, you will get a Not Found error. We would like users to access about instead. Our rewrite rules will allow this very functionality.

After the first line, add the following.