Select Page

Creation

Apache’s mod_rewrite module allows you to rewrite URLs in a cleaner type, translating human-readable paths into code-friendly question strings. It additionally allows you to rewrite URLs in keeping with stipulations.

An .htaccess record allows you to create and practice rewrite laws with out getting access to server configuration information. By means of striking the .htaccess record within the root of your internet web site, you’ll arrange rewrites on a per-site or per-directory foundation.

On this educational, you can permit mod_rewrite and use .htaccess information to create a fundamental URL redirection, after which discover a few complex use circumstances.

Necessities

To apply this educational, you’ll want:

Step 1 — Enabling mod_rewrite

To ensure that Apache to grasp rewrite laws, we first wish to turn on mod_rewrite. It is already put in, however it is disabled on a default Apache set up. Use the a2enmod command to permit the module:

This may occasionally turn on the module or warn you that the module is already enabled. To position those adjustments into impact, restart Apache.

  • sudo systemctl restart apache2

mod_rewrite is now totally enabled. In your next step we can arrange an .htaccess record that we will use to outline rewrite laws for redirects.

Step 2 — Atmosphere Up .htaccess

Because of this, .htaccess is significant on your internet utility’s safety. The duration that precedes the filename guarantees that the record is hidden.

Word: Any laws that you’ll installed an .htaccess record can also be additionally put at once into server configuration information. If truth be told, the official Apache documentation recommends the usage of server configuration information as an alternative of .htaccess as a result of Apache processes it sooner that approach.

Then again, on this easy instance, the efficiency building up can be negligible. Moreover, atmosphere laws in .htaccess is handy, particularly with more than one web sites at the similar server. It does now not require a server restart for adjustments to take impact and it does now not require root privileges to edit the ones laws, simplifying repairs and and making adjustments conceivable with unprivileged account. Some widespread open-source device, like WordPress and Joomla, incessantly depends on an .htaccess record for the device to switch and create further laws on call for.

Sooner than you get started the usage of .htaccess information, you can wish to arrange and safe a couple of extra settings.

By means of default, Apache prohibits the usage of an .htaccess record to use rewrite laws, so first you wish to have to permit adjustments to the record. Open the default Apache configuration record the usage of nano or your favourite textual content editor.

  • sudo nano /and so forth/apache2/sites-available/000-default.conf

Within that record, you’ll discover a block beginning at the first line. Within that block, upload the next new block so your configuration record looks as if the next. Make certain that all blocks are correctly indented.

/and so forth/apache2/sites-available/000-default.conf


        Choices Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    

    . . .

Save and shut the record. To position those adjustments into impact, restart Apache.

  • sudo systemctl restart apache2

Now, create an .htaccess record within the internet root.

  • sudo nano /var/www/html/.htaccess

Upload this line on the most sensible of the brand new record to turn on the rewrite engine.

/var/www/html/.htaccess

RewriteEngine on

Save the record and go out.

You presently have an operational .htaccess record which you’ll use to control your internet utility’s routing laws. In your next step, we can create pattern site information that we will use to exhibit rewrite laws.

Step 3 — Configuring URL Rewrites

Right here, we can arrange a fundamental URL rewrite which converts beautiful URLs into exact paths to pages. Particularly, we can permit customers to get right of entry to http://your_server_ip/about, however show a web page known as about.html.

Start by way of making a record named about.html within the internet root.

  • sudo nano /var/www/html/about.html

Replica the next HTML code into the record, then save and shut it.

/var/www/html/about.html


    
        About Us

About Us

You’ll be able to get right of entry to this web page at http://your_server_ip/about.html, however understand that in the event you attempt to get right of entry to http://your_server_ip/about, you’ll see a 404 Now not Discovered error. To get right of entry to the web page the usage of /about as an alternative, we will create a rewrite rule.

All RewriteRules apply this layout:

Common RewriteRule construction

RewriteRule development substitution [flags]
  • RewriteRule specifies the directive.
  • development is a regular expression that fits the required string from the URL, which is what the viewer sorts within the browser.
  • substitution is the trail to the true URL, i.e. the trail of the record Apache servers.
  • flags are not obligatory parameters that may alter how the rule of thumb works.

Let’s create our URL rewrite rule. Open up the .htaccess record.

  • sudo nano /var/www/html/.htaccess

After the primary line, upload the RewriteRule marked in pink and save the record.

/var/www/html/.htaccess

RewriteEngine on
RewriteRule ^about$ about.html [NC]

On this case, ^about$ is the development, about.html is the substitution, and [NC] is a flag. Our instance makes use of a couple of characters with particular that means:

  • ^ signifies the beginning of the URL, after your_server_ip/.
  • $ signifies the tip of the URL.
  • about fits the string “about”.
  • about.html is the true record that the person accesses.
  • [NC] is a flag that makes the rule of thumb case insensitive.

You’ll be able to now get right of entry to http://your_server_ip/about to your browser. If truth be told, with the rule of thumb proven above, the next URLs will level to about.html:

  • http://your_server_ip/about, on account of the rule of thumb definition.
  • http://your_server_ip/About, for the reason that rule is case insensitive.
  • http://your_server_ip/about.html, for the reason that unique correct filename will all the time paintings.

Then again, the next is not going to paintings:

  • http://your_server_ip/about/, for the reason that rule explicitly states that there could also be not anything after about, since the $ personality seems after about.
  • http://your_server_ip/touch, as it may not fit the about string within the rule.

You presently have an operational .htaccess record with a fundamental rule that you’ll alter and prolong on your wishes. Within the following sections, we can display two further examples of frequently used directives.

Instance 1 — Simplifying Question Strings with RewriteRule

Internet programs incessantly employ question strings, which can be appended to a URL the usage of a query mark (?) after the cope with. Separate parameters are delimited the usage of an ampersand (&). Question strings could also be used for passing further knowledge between person utility pages.

As an example, a seek consequence web page written in PHP might use a URL like http://instance.com/effects.php?merchandise=blouse&season=summer time. On this instance, two further parameters are handed to the imaginary consequence.php utility script: merchandise, with the worth blouse, and season with the worth summer time. The appliance might use the question string data to construct the correct web page for the customer.

Apache rewrite laws are incessantly hired to simplify such lengthy and unpleasent hyperlinks because the above into pleasant URLs which can be more uncomplicated to sort and interpret visually. On this instance, we want to simplify the above hyperlink to turn out to be http://instance.com/blouse/summer time. The blouse and summer time parameter values are nonetheless within the cope with, however with out the question string and script identify.

This is one rule to put in force this:

Easy substition

RewriteRule ^blouse/summer time$ effects.php?merchandise=blouse&season=summer time [QSA]

The blouse/summer time is explicitly matched within the asked cope with and Apache is informed to serve effects.php?merchandise=blouse&season=summer time as an alternative.

The [QSA] flags are frequently utilized in rewrite laws. They inform Apache to append any further question string to the served URL, so if the customer sorts http://instance.com/blouse/summer time?web page=2 the server will reply with effects.php?merchandise=blouse&season=summer time&web page=2. With out it, the extra question string would get discarded.

Whilst this system achieves the required impact, each the article identify and season are hardcoded into the rule of thumb. This implies the rule of thumb is not going to paintings for some other pieces, like pants, or seasons, like wintry weather.

To make the rule of thumb extra generic, we will use regular expressions to compare portions of the unique cope with and use the ones portions in a substitution development. The changed rule will then glance as follows:

Easy substition

RewriteRule ^([A-Za-z0-9]+)/(summer time|wintry weather|fall|spring) effects.php?merchandise=$1&season=$2 [QSA]

The primary common expression team in parenthesis fits a string containing alphanumeric characters and numbers like blouse or pants and saves the matched fragment because the $1 variable. The second one common rexpression team in parenthesis fits precisely summer time, wintry weather, fall, or spring, and in a similar fashion saves the matched fragment as $2.

The matched fragments are then used within the ensuing URL in merchandise and season variables as an alternative of hardcoded blouse and summer time values we used sooner than.

The above will convert, as an example, http://instance.com/pants/summer time into http://instance.com/effects.php?merchandise=pants&season=summer time. This case may be long run evidence, permitting mutliple pieces and seasons to be as it should be rewritten the usage of a unmarried rule.

Instance 2 — Including Stipulations with Common sense The usage of RewriteConds

Rewrite laws don’t seem to be essentially all the time evaluated one after the other with none barriers. The RewriteCond directive shall we us upload stipulations to our rewrite laws to keep watch over when the foundations can be processed. All RewriteConds abide by way of the next layout:

Common RewriteCond construction

RewriteCond TestString Situation [Flags]
  • RewriteCond specifies the RewriteCond directive.
  • TestString is the string to check in opposition to.
  • Situation is the development or situation to compare.
  • Flags are not obligatory parameters that can alter the situation and analysis laws.

If a RewriteCond evaluates to true, the RewriteRule instantly following can be regarded as. If it may not, the rule of thumb can be discarded. More than one RewriteCond could also be used one after some other and, with default behaviour, all should review to true for the next rule to be regarded as.

For example, shall we say you want to redirect all requests to non-existent information or directories for your web site again to the house web page as an alternative of unveiling the usual 404 Now not Discovered error web page. This can also be completed with following stipulations laws:

Redirect all requests to non-existent information and directories to house web page

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /

With the above:

  • %{REQUEST_FILENAME} is the string to test. On this case, it is the asked filename, which is a gadget variable out there for each and every request.
  • -f is a integrated situation which verifies if the asked identify exists on disk and is a record. The ! is a negation operator. Blended, !-f evaluates to true provided that a specified identify does now not exist or isn’t a record.
  • In a similar fashion, !-d evaluates to true provided that a specified identify does now not exist or isn’t a listing.

The RewriteRule at the ultimate line will come into impact just for requests to non-existent information or directories. The RewriteRule itself could be very easy and redirects each and every request to the / site root.

mod_rewrite allows you to create human-readable URLs. On this educational, you discovered learn how to use the RewriteRule directive to redirect URLs, together with ones with question strings. You additionally discovered learn how to conditionally redirect URLs the usage of the RewriteCond directive.

If you would like to be told extra about mod_rewrite, check out Apache’s mod_rewrite Introduction and Apache’s official documentation for mod_rewrite.