Apache Mod_rewrite Http To Https

Posted on  by admin

Table of Contents

This document supplements the modrewrite reference documentation.It describes perhaps one of the most important concepts about modrewrite - namely, when to avoid using it. Modrewrite should be considered a last resort, when other alternatives are found wanting. Using it when there are simpler alternatives leads to configurations which are confusing, fragile, and hard to maintain. Apache 2.4 documentation: When not to use modrewrite. In this case you should not even have a DocumentRoot defined. This is the absolute simplest use of the modalias Redirect directive, and the official documentation tells you eaxactly how to do it.

Introduction

Apache's mod_rewrite can be used to manipulate URLs. It is compiled into the base Apache Web Server.This module provides the ability to manipulate URLs prior to determining the appropriate file or handing off to a script. It can help you, if you want to offer different URLs for the same file. This is most commonly used when a visitor goes to a certain web address, but the server returns a different page.This module uses a rule-based rewriting engine to rewrite requested URLs on the fly. It supports an unlimited number of rules to provide a really flexible and powerful URL manipulation mechanism. It can hide sensitive information, such as query strings, from URL requests. This can potentially enhance website safety.

In this tutorial, we will explain how to enable mod_rewrite and demonstrate some common ways to use it in Apache on CentOS 7.

Requirements

  • A server running CentOS 7

Install Apache

Before we begin with the mod_rewrite module setup, we need to install the Apache web server.

To install Apache, run the following command:

After installing Apache, start the httpd service and enable it to start automatically on boot.

We can do this using the following commands:

Next, we should allow access to the default Apache port 80 (HTTP) using firewalld.

We can do this by running the following command:

Now, reload the firewall service for the changes to take effect.

Enable mod_rewrite Module

The mod_rewrite module is enabled by default on CentOS 7. If you find it is not enabled on your server, you can enable it by editing 00-base.conf file located in /etc/httpd/conf.modules.d/ directory.

Apache mod_rewrite http to https outlook

Add or uncomment the following line:

Apache

Apache Rewriteengine Http To Https

Save and close the file, then restart the httpd service:

Enable .htaccess File

Once the mod_rewrite module has been activated, you can set up your URL rewrites by creating an .htaccess file in your default document root directory.A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web server.Before we begin, we need to allow Apache to read .htaccess files located under the /var/www/html directory.

You can do this by editing httpd.conf file:

Find the section <directory /var/www/html> and change AllowOverride None to AllowOverride All

Apache 2.4 Rewrite

Save and exit.

Now restart Apache to put the change into effect:

Mod_rewrite

Configure Rewrite Module

In this section, we will explain basic mod_rewrite syntax and give some examples.

You can write RewriteRules using the following format:

  • RewriteRule: This directive specifies the name of the the mod_rewrite directive that you want to use.
  • Pattern: This directive specifies a regular expression that matches the desired string
  • Substitution: This directive specifies the path of the actual URL of the page with the information you want to display.
  • Flags: A flag is a tag at the end of the Rewrite Rule directive that specifies optional parameters that can modify the rule.

Let's discuss RewriteRules with some examples:

Apache Mod_rewrite Http To Https Yahoo

Redirect www to non-www

If you want to redirect users from www to a plain non-www domain, you will need to create .htaccess file in Apache document root directory.

Change directories to your Document root:

Create the .htaccess file:

Add the following content:

Save and exit the file.

We can use curl to test that the www domain redirects to the non-www domain:

You should see the following output:

Above output shows the non-www redirect location http://yourdomain.com/

Redirect non-www to www

If you want to redirect users from a plain non-www domain to a www domain, add the following content to your .htaccess file:

Add the following content:

Save and exit the file.

Now, use curl command to ensure that the non-www domain redirects to the www domain:

You should see the following output:

Above output shows the www redirect location http://www.yourdomain.com/

Redirect All Website Pages

If you want to redirect all pages from 'olddomain.com' to 'newdomain.com', edit the .htaccess file:

Add the following content:

Save and exit the file.

Now, use curl to test that the 'www.olddomain.com' domain redirects to the 'www.newdomain.com' domain:

You should get a 301 Moved Permanently response that shows you the new domain redirect location.

Deny File Type Access

If you want to deny users to access specific file types such as: .pdf, .css, .gif, .png, or .bmp then edit your .htacces file:

Add the following content:

Save and exit the file.

Summary

Those are just a few examples of how mod_rewrite can be used. If you have questions about these examples please let us know below. You are also welcome to post in the ProfitBricks DevOps Community section of this site.

This document supplements the mod_rewritereference documentation. It provides a few advanced techniques using mod_rewrite.

Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration.

URL-based sharding across multiple backends

Description:

A common technique for distributing the burden of server load or storage space is called 'sharding'. When using this method, a front-end server will use the url to consistently 'shard' users or objects to separate backend servers.

Solution:

A mapping is maintained, from users to target servers, in external map files. They look like:

We put this into a map.users-to-hosts file. The aim is to map;

/u/user1/anypath

to

thus every URL path need not be valid on every backend physical host. The following ruleset does this for us with the help of the map files assuming that server0 is a default server which will be used if a user has no entry in the map:

See the RewriteMap documentation for more discussion of the syntax of this directive.

On-the-fly Content-Regeneration

Mod_rewrite
Description:

We wish to dynamically generate content, but store it statically once it is generated. This rule will check for the existence of the static file, and if it's not there, generate it. The static files can be removed periodically, if desired (say, via cron) and will be regenerated on demand.

Solution:
This is done via the following ruleset:

The -U operator determines whether the test string (in this case, REQUEST_URI) is a valid URL. It does this via a subrequest. In the event that this subrequest fails - that is, the requested resource doesn't exist - this rule invokes the CGI program /regenerate_page.cgi, which generates the requested resource and saves it into the document directory, so that the next time it is requested, a static copy can be served.

In this way, documents that are infrequently updated can be served in static form. if documents need to be refreshed, they can be deleted from the document directory, and they will then be regenerated the next time they are requested.

Load Balancing

Description:

We wish to randomly distribute load across several servers using mod_rewrite.

Solution:

We'll use RewriteMap and a list of servers to accomplish this.

serverlist.txt will contain a list of the servers:

If you want one particular server to get more of the load than the others, add it more times to the list.

Discussion

Apache comes with a load-balancing module - mod_proxy_balancer - which is far more flexible and featureful than anything you can cobble together using mod_rewrite.

Structured Userdirs

Description:

Some sites with thousands of users use a structured homedir layout, i.e. each homedir is in a subdirectory which begins (for instance) with the first character of the username. So, /~larry/anypath is /home/l/larry/public_html/anypath while /~waldo/anypath is /home/w/waldo/public_html/anypath.

Solution:

We use the following ruleset to expand the tilde URLs into the above layout.

Redirecting Anchors

Description:

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.

Apache Mod_rewrite Http To Https Gmail

Solution:

Use the [NE] flag on the RewriteRule. NE stands for No Escape.

Discussion:
This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.

Time-Dependent Rewriting

Description:

We wish to use mod_rewrite to serve different content based on the time of day.

Solution:

There are a lot of variables named TIME_xxx for rewrite conditions. In conjunction with the special lexicographic comparison patterns <STRING, >STRING and =STRING we can do time-dependent redirects:

This provides the content of foo.day.html under the URL foo.html from 07:01-18:59 and at the remaining time the contents of foo.night.html.

mod_cache, intermediate proxies and browsers may each cache responses and cause the either page to be shown outside of the time-window configured. mod_expires may be used to control this effect. You are, of course, much better off simply serving the content dynamically, and customizing it based on the time of day.

Set Environment Variables Based On URL Parts

Description:

At time, we want to maintain some kind of status when we perform a rewrite. For example, you want to make a note that you've done that rewrite, so that you can check later to see if a request can via that rewrite. One way to do this is by setting an environment variable.

Solution:

Use the [E] flag to set an environment variable.

Later in your ruleset you might check for this environment variable using a RewriteCond:

Http

Note that environment variables do not survive an external redirect. You might consider using the [CO] flag to set a cookie.

© 2018 The Apache Software Foundation
Licensed under the Apache License, Version 2.0.
https://httpd.apache.org/docs/2.4/en/rewrite/advanced.html