Apache module mod_rewrite

- Andrés Cruz

En español

Apache module mod_rewrite

The MOD_REWRITE is a module provided by the Apache server that allows creating alternative URLs to the dynamic URLs generated by the way our web applications are programmed; in such a way that they are easier to remember, more readable and also better indexed by search engines; and this is an important factor to consider at the time of SEO.

Enabling MOD_REWRITE in Apache

It all comes down to 2 easy steps: run a command on the command line and modify the directives in an Apache configuration file.

The a2enmod command is used to enable modules in Apache; to enable the Apache rewrite module we execute:

a2enmod rewrite

Later in the route:

/etc/apache2/sites-available/default

We look for the lines that say:

AllowOverrideNone

And we change them all to:

Allow Override All

In such a way that we allow the rewriting of URLs; now we restart Apache with the following instruction:

/etc/init.d/apache2 restart

either

service httpd stop service httpd start

Validating the operation of MOD_REWRITE

To test that the activation of the rewrite module worked; we create an .htaccess file in the root of our server; the .htaccess file is made up of rules based on regular expressions; which Apache will process. In this example we will make a redirect using a simple rule; we copy the following lines in the .htaccess.

RewriteEngine On RewriteRule test.html http://www.google.com [R]

We create a test HTML document in the root of our server; It doesn't need to have any content, we'll call it test.html.

We place the following URL <our-host>/test.html in our browser.

Where <our-host> is the server where we are working; if the same is our machine; will be localhost.

If all goes well Apache will have redirected us to the Google home page.

What have we done?

To answer this question we must explain the rules contained in the .htaccess:

  • The first line "turn on" or allow rewrite.
  • The second and last line we are creating a rule with RewriteRule where we indicate that when it "finds" test.html from the root, it redirects us to google.com; finally, the [R] flag forces a URL from our server or internal to our server to be redirected to an external URL.
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 2d 13:25!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!