Rewriterule online

RewriteRule | Online How To

RegEx 101

The first tool is RegEx 101. It’s a very fancy tool that not only allows you to write your regex online, but also allows you to test the regex on various strings to make sure that the regex will work correctly. The other added bonus is that it has some useful help information.

As noted previously, rewrite rules execute after the RewriteEngine on line in the .htaccess file. We often see customers place rewrite rules after Drupal's core rewrite rules (which route the request to be handled by Drupal). These rules will typically not be evaluated, because Drupal's default request handler rules will take precedence. If you are adding rewrite rules to Drupal, they should typically be:

Building the Conditions

The first step to rewriting a path is to create a condition which will either pass or fail. This condition will then cause the rule to process, or not. Regular expressions power each condition, and are based on a group of common variables.

In some cases where simple path redirection is required, you can skip setting a RewriteCond and a RewriteRule can be passed with a simple condition. Any other conditions, including conditions based on the HTTP_HOST, must be done through a RewriteCond line.

Syntax

RewriteRule


This only applies to the pattern, not to the substitution. Other characters that require escaping (referred to as "metacharacters") follow, with their meaning in brackets afterwards:

  • . (any character)
  • * (zero of more of the preceding)
  • + (one or more of the preceding)
  • {} (minimum to maximum quantifier)
  • ? (ungreedy modifier)
  • ! (at start of string means "negative pattern")
  • ^ (start of string, or "negative" if at the start of a range)
  • $ (end of string)
  • [] (match any of contents)
  • - (range if used between square brackets)
  • () (group, backreferenced group)
  • | (alternative, or)
  • \ (the escape character itself)

Using regular expressions, it is possible to search for all sorts of patterns in URLs and rewrite them when they match. Time for another example - we wanted earlier to be able to indentify this URL and rewrite it:

http://www.pets.com/parrots/norwegian-blue/

And we want to be able to tell the server to interpret this as the following, but for all products:

And we can do that relatively simply, with the following rule:

With this rule, any URL that starts with "parrots" followed by a slash (parrots/), then one or more (+) of any combination of letters, numbers and hyphens ([A-Za-z0-9-]) (note the hyphen at the end of the selection of characters within square brackets - it must be added there to be treated literally rather than as a range separator). We reference the product name in brackets with $1 in the substitution.

We can make it even more generic, if we want, so that it doesn't matter what directory a product appears to be in, it is still sent to the same script, like so:

As you can see, we've replaced "parrots" with a pattern that matches letter and hyphens. That rule will now match anything in the parrots directory or any other directory whose name is comprised of at least one or more letters and hyphens.

Flags

RewriteBase /
RewriteRule ^a.html$ b.html
RewriteRule ^b.html$ a.html

# Конец .htaccess


Отгадка:

.

.

.

Как работает mod_rewrite. Флаг [R]


Флаг [R] сообщает Apache, что нужно выполнить не внутренний, а внешний редирект. Чем отличается внешний редирект от внутреннего? Внутренний редирект просто изменяет путь до файла, который будет отдан пользователю, при этом пользователь считает, что получает тот файл, который он изначально запросил. При внешнем же редиректе Apache вместо содержимого файла возвращает пользователю статус ответа 301 или 302 и сообщает ссылку, по которой браузер должен обратиться для получения файла.

Казалось бы, при обработке флага [R] Apache должен сразу прекратить обработку RewriteRule и вернуть пользователю внешний редирект. Однако давайте вспомним фантастический пример из раздела «Как работает RewriteRule». В нем мы сначала указали флаг [R], обозначив необходимость внешнего редиректа, после чего продолжили изменять ссылку следующими RewriteRule.

Именно так и работает Apache при указании внешнего редиректа. Он просто «помечает» себе, что после выполнения всех правил необходимо вернуть статус 302 (по умолчанию), но при этом продолжает выполнение всех RewriteRule дальше по списку. Мы можем и дальше изменять запрос как нам нужно, единственное, что не получится — сделать редирект обратно внутренним.

Тем не менее, вряд ли вы хотите после отдачи внешнего редиректа каким-либо образом изменять его. Поэтому рекомендуется при употреблении флага [R] указывать его совместно с [L]:

# Можно использовать просто внешнюю ссылку
RewriteRule ^bj/(.*) http://blackjack.example.com/$1 [L]


Вместо использования флага [R] можно указывать просто внешнюю ссылку. В этом случае Apache сам догадается, что необходимо сделать внешний редирект. Здесь, как и с в случае с явным указанием флага [R], рекомендуется использовать флаг [L].

  • Если внешний редирект ведет на тот же сайт, лучше использовать флаг [R] без указания полной ссылки (иными словами, использовать относительный внешний редирект). Это сделает правило независимым от имени сайта.
  • Если же внешний редирект ведет на другой сайт, иначе, как указав полную внешнюю ссылку, это сделать не получится.

If this option is enabled, all child configurations will inherit
the configuration of the current configuration. It is equivalent to
specifying RewriteOptions Inherit in all child
configurations. See the Inherit option for more details
on how the parent-child relationships are handled.
Available in Apache HTTP Server 2.4.8 and later.

Like InheritDown above, but the rules from the current
scope are applied before rules specified in any child's
scope.
Available in Apache HTTP Server 2.4.8 and later.

This option forces the current and child configurations to ignore
all rules that would be inherited from a parent specifying
InheritDown or InheritDownBefore.
Available in Apache HTTP Server 2.4.8 and later.

By default, mod_rewrite will ignore URLs that map to a
directory on disk but lack a trailing slash, in the expectation that
the mod_dir module will issue the client with a redirect to
the canonical URL with a trailing slash.

When the DirectorySlash directive
is set to off, the AllowNoSlash option can be enabled to ensure
that rewrite rules are no longer ignored. This option makes it possible to
apply rewrite rules within .htaccess files that match the directory without
a trailing slash, if so desired.
Available in Apache HTTP Server 2.4.0 and later.

When RewriteRule
is used in VirtualHost or server context with
version 2.2.22 or later of httpd, mod_rewrite
will only process the rewrite rules if the request URI is a URL-path. This avoids
some security issues where particular rules could allow
"surprising" pattern expansions (see CVE-2011-3368
and CVE-2011-4317).
To lift the restriction on matching a URL-path, the
AllowAnyURI option can be enabled, and
mod_rewrite will apply the rule set to any
request URI string, regardless of whether that string matches
the URL-path grammar required by the HTTP specification.
Available in Apache HTTP Server 2.4.3 and later.

Security Warning

Enabling this option will make the server vulnerable to
security issues if used with rewrite rules which are not
carefully authored. It is strongly recommended
that this option is not used. In particular, beware of input
strings containing the '@' character which could
change the interpretation of the transformed URI, as per the
above CVE names.

With this option, the value of RewriteBase is copied from where it's explicitly defined
into any sub-directory or sub-location that doesn't define its own
RewriteBase. This was the
default behavior in 2.4.0 through 2.4.3, and the flag to restore it is
available Apache HTTP Server 2.4.4 and later.

When a relative substitution is made
in directory (htaccess) context and RewriteBase has not been set, this module uses some
extended URL and filesystem context information to change the
relative substitution back into a URL. Modules such as
mod_userdir and mod_alias
supply this extended context info.


Теперь при обращение к "www.test.com" все файлы будут браться из “test.com/new”

This is simple mod rewrite rule generator which lets you to generate SEO friendly URLs for dynamic URLs.

I Hope above online .htaccess mod rewrite rule generators will be helpful to Bloggers and Webmasters.

Наверх