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
1 2 |
sudo apt-get update sudo apt-get install apache2 |
Step 2 — Enabling mod_rewrite
1 2 |
sudo a2enmod rewrite sudo service apache2 restart |
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.
1 |
sudo nano /etc/apache2/sites-enabled/000-default.conf |
Inside that file, you will find the block on line 1. Inside of that block, add the following block:
1 2 3 4 5 6 7 8 9 10 |
# /etc/apache2/sites-available/default <VirtualHost *:80> <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> . . . </VirtualHost> |
Now, create the .htaccess file.
1 |
sudo nano /var/www/html/.htaccess |
Add this first line at the top of the new file to activate the RewriteEngine.
1 2 |
/var/www/html/.htaccess RewriteEngine on |
Save and exit the file. To ensure that other users may only read your .htaccess, run the following command to update permissions.
1 |
sudo chmod 644 /var/www/html/.htaccess |
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.
1 |
sudo nano /var/www/html/about.html |
Copy the following code into the HTML page.
1 2 3 4 5 6 7 8 9 |
# /var/www/html/about.html <html> <head> <title>About Us</title> </head> <body> <h1>About Us</h1> </body> </html> |
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.
1 |
sudo nano /var/www/html/.htaccess |
After the first line, add the following.
1 2 |
/var/www/html/.htaccess RewriteRule ^about$ about.html [NC] |