Mod rewrite как включить centos
Перейти к содержимому

Mod rewrite как включить centos

  • автор:

Настройка mod_rewrite на веб-сервере Apache в CentOS 7

Apache – это модульный веб-сервер (то есть, он позволяет настраивать функции путём включения и отключения модулей). Это предоставляет администраторам возможность максимально точно подгонять настройки веб-сервера под требования приложений.

Данное руководство поможет установить Apache на сервер CentOS 7 и настроить поддержку mod_rewrite.

Требования

  • Сервер CentOS 7.
  • Пользователь с доступом к sudo (подробности можно найти в руководстве Создание пользователя sudo в CentOS).

1: Установка Apache

Apache можно установить с помощью пакетного менеджера yum.

sudo yum install httpd

Команда запросит подтверждения:

Чтобы продолжить установку, введите Y и нажмите Enter.

Запустите демон Apache (это автономный процесс, который создаёт пул дочерних процессов или потоков для обработки запросов):

sudo systemctl start httpd

Чтобы убедиться в том, что запуск Apache прошёл успешно, введите:

sudo systemctl status httpd
. . .
systemd[1]: Starting The Apache HTTP Server.
systemd[1]: Started The Apache HTTP Server .

Сервер Apache успешно установлен. Теперь нужно сосредоточить внимание на модулях.

2: Модуль mod_rewrite

В CentOS 7 модуль mod_rewrite поддерживается по умолчанию. Проверьте, так ли это. Используйте команду httpd с флагом –M, чтобы вывести список включенных модулей:

httpd -M
. . .
remoteip_module (shared)
reqtimeout_module (shared)
rewrite_module (shared)
setenvif_module (shared)
slotmem_plain_module (shared)
. . .

Если в списке нет модуля rewrite_module, включите его вручную. Отредактируйте 00-base.conf.

sudo vi /etc/httpd/conf.modules.d/00-base.conf

Когда текстовый редактор откроется, перейдите в режим вставки (нажмите i) и добавьте в файл:

#
# This file loads most of the modules included with the Apache HTTP
# Server itself.
#
. . .
LoadModule rewrite_module modules/mod_rewrite.so
. . .

Чтобы выйти из режима вставки, нажмите Esc. Нажмите 😡 и Enter, чтобы сохранить и закрыть файл.

Обновите настройки веб-сервера:

sudo systemctl restart httpd

Теперь можно приступать к созданию файла .htaccess.

3: Создание файла .htaccess

Файл .htaccess определяет индивидуальные директивы Apache (включая RewriteRule) для каждого отдельного домена.

Примечание: В Linux с символа точки начинаются имена скрытых файлов.

Сначала нужно включить поддержку файлов .htaccess. Дляэтого отредактируйте директиву AllowOverride:

sudo vi /etc/httpd/conf/httpd.conf

Найдите в этом файле раздел <Directory /var/www/html>. Он содержит AllowOverride. Измените значение None на All.

. . .
<Directory /var/www/html>
. . .
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be «All», «None», or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
. . .
</Directory>
. . .

Сохраните и закройте файл. Перезапустите Apache:

sudo systemctl restart httpd

Создайте файл .htaccess в стандартном каталоге document root (/var/www/html):

sudo vi /var/www/html/.htaccess

Добавьте в начало файла следующую строку, чтобы активировать RewriteEngine. Так Apache сможет обрабатывать правила перезаписи.

Теперь на сервере есть файл .htaccess, который позволяет установить правила перезаписи URL-ов. Прежде чем приступить к написанию этих правил, нужно ознакомиться с синтаксисом mod_rewrite.

4: Синтаксис RewriteRule

Директива RewriteRule позволяет преобразовать запросы Apache на основе URL-адреса. Файл .htaccess может содержать множество правил перезаписи. Apache применяет правила в том порядке, в котором они определены в файле. RewriteRule имеет такую структуру:

RewriteRule Pattern Substitution [Flags]

  • RewriteRule: собственно директива.
  • Pattern: библиотека PCRE (Perl Compatible Regular Expression). Больше информации об этом можно найти здесь.
  • Substitution: куда отправить поступивший запрос.
  • [Flags]: опциональные параметры, изменяющие поведение правила. Список доступных флагов можно найти в документации Apache.

Директива RewriteRule очень важна для mod_rewrite.

5: Синтаксис RewriteCond

Директива RewriteCond позволяет добавлять условия в правило перезаписи. Условие перезаписи состоит из следующих компонентов:

RewriteCond TestString Condition [Flags]

  • RewriteCond: директива.
  • TestString: строка, которую нужно проверить.
  • Condition: шаблон, которому должна отвечать строка.
  • [Flags]: опциональные параметры.

Благодаря директиве RewriteCond Apache пвыполняет перезапись только в том случае, если определённое условие истинно.

6: Создание тестового файла

Создайте простое правило, которое позволит пользователям получать доступ к странице about.html без расширения (.html). Для начала создайте файл about.html в каталоге document root:

sudo vi /var/www/html/about.html

Скопируйте следующий код HTML и вставьте в файл:

Сохраните и закройте файл.

Откройте браузер и перейдите по ссылке:

На экране появится страница с заголовком About Us. Попробуйте удалить из ссылки расширение .html. Браузер отобразит сообщение об ошибке 404 Not Found. По умолчанию Apache получает доступ к компонентам с помощью полного имени файла. Модуль mod_rewrite может изменить это поведение.

7: Настройка RewriteRule

Теперь попробуйте сделать так, чтобы посетители страницы About Us могли получить к ней доступ без расширения .html в ссылке. Для этого нужно создать правило.

sudo vi /var/www/html/.htaccess

Найдите строку RewriteEngine On и добавьте после неё следующую строку:

RewriteRule ^about$ about.html [NC]

Сохраните и закройте файл.

Теперь в ссылке на страницу About Us не будет расширения:

Рассмотрим это правило подробнее:

  • ^about$ – шаблон, с которым совпадает URL, и который пользователи вводят в браузере. В данном примере используются метасимволы, благодаря которым можно чётко обозначить местонахождение шаблона: символ ^ определяет начало шаблона (после server_domain_or_IP/), а & – конец.
  • about.html – путь к файлу, который обслуживает Apache, когда встречает этот шаблон.
  • [NC] – флаг, который отключает учет регистра, благодаря чему пользователи могут вводить адрес как в верхнем, так и в нижнем регистре. К примеру, URL-адреса serverdomainor_IP/about, serverdomainor_IP/About и serverdomainor_IP/ABOUT отобразят страницу about.html.

Общие шаблоны

Итак, теперь вы знаете основы написания правил перезаписи. Рассмотрим два дополнительных примера.

Примечание: Для тестирования можно создать пару дополнительных файлов.

Пример 1: Упрощение строки запросов с помощью RewriteRule

Приложения часто используют строки запросов. Эти строки находятся в URL-адресе, начиная с вопросительного знака (?) и заканчивая амперсандом (&). Обрабатывая правила перезаписи, Apache игнорирует эти два символа. К примеру, URL страницы результатов поиска, написанной на PHP, может выглядеть следующим образом:

Конечно, пользователям будет гораздо удобнее, если ссылка будет чистой:

Этого можно добиться двумя способами: с помощью простой замены или группирования параметров.

1: Простая замена

Создайте правило, выполняющее простую замену, чтобы ссылка стала чистой:

RewriteRule ^shoes/women$ results.php?item=shoes&type=women

Это правило вместо results.php?item=shoes&type=women будет использовать shoes/women.

2: Сопоставление и группирование

В некоторых ситуациях нужно оптимизировать строку запросов (к примеру, чтобы она включала несколько видов обуви). Для этого нужно:

  • Задать набор параметров, разделив их с помощью символа вертикальной черты | (логический оператор OR).
  • Сгруппировать все заданные параметры с помощью круглых скобок (), а затем сослаться на группу с помощью переменной $1 (где 1 – номер группы параметров).

В результате получится такое правило:

RewriteRule ^shoes/(men|women|youth) results.php?item=shoes&type=$1

Это правило добавляет в URL новый сегмент.

3: Совпадение наборов символов

Чтобы пользователь мог открыть чистый URL любого раздела сайта (не только /shoes), нужно:

  • Написать регулярное выражение, совпадающее со всеми алфавитно-цифровыми символами. В квадратных скобках указывается поисковой шаблон (в данном случае он включает все символы), а символ + указывет что каждый символ в шаблоне может повторяться неограниченное количество раз.
  • Сгруппировать этот набор символов и присвоить ему $2.

RewriteRule ^([A-Za-z0-9]+)/(men|women|youth) results.php?item=$1&type=$2

Это правило преобразует:

4: Дополнительная строка запроса

Это позволит вам устранить ряд потенциальных проблем. Попробуйте преобразовать:

При текущих настройках вы не сможете перейти на page=2. Это можно исправить с помощью флага QSA, который позволяет комбинировать строки запросов. Отредактируйте правило следующим образом:

RewriteRule ^([A-Za-z0-9]+)/(men|women|youth) results.php?item=$1&type=$2 [QSA]

Пример 2: Условия RewriteCond

Теперь рассмотрим подробнее директиву RewriteCond. Если условие перезаписи истинно, Apache обработает следующее за ним правило RewriteRule.

1: Страница по умолчанию

Ранее вы видели, что в случае если запрашиваемой страницы не существует, Apache возвращает страницу ошибки 404 Not Found. Однако вместо этого Apache может перенаправлять все подобные запросы на домашнюю страницу. Добавьте следующее условие, чтобы убедиться, что запрашиваемый файл существует:

RewriteCond % !-f
RewriteRule ^admin/(.*)$ /admin/home

Теперь все ссылки на несуществующие страницы будут перенаправлены на /admin/home.

Рассмотрим вышеприведённое правило по частям:

  • % проверяет запрашиваемую строку.
  • !-f: оператор ! (not) указывает, что если запрашиваемого файла не существует, веб-сервер должен выполнить следующее правило переадресации.
  • RewriteRule перенаправляет запрос на /admin/home.

Также можно задать ErrorDocument, на который будут отправляться все запросы на несуществующие страницы. Создайте правило ErrorDocument и перенаправьте все ошибки 404 на страницу error.html:

ErrorDocument 404 /error.html

Теперь все запросы, которые получили ошибку 404, будут переадресованы на error.html.

2: Ограничение доступа по IP

RewriteCond позволяет ограничивать доступ к сайту по IP-адресу.

К примеру, это правило заблокирует весь трафик, кроме 198.51.100.24:

RewriteCond % !^(198\.51\.100\.24)$
RewriteRule (.*) — [F,L]

Если сайт будет запрашиваться другими IP-адресами, трафик будет заблокирован.

Вкратце рассмотрим это правило:

  • % – строка адреса.
  • !^(198\.51\.100\.24)$ – IP-адрес. Обратный слеш позволяет обойти метасимвол «.».

Чтобы заблокировать доступ к сайту для определенного IP, используйте такое правило:

RewriteCond % ^(198\.51\.100\.24)$
RewriteRule (.*) — [F,L]

Существует множество способов управления доступом к сайту, и файл .htaccess – один из самых простых.

Заключение

Модуль mod_rewrite – один из основных компонентов Apache.

В данном руководстве вы научились создавать файл .htaccess и работать с директивами RewriteRule и RewriteCond.

How to install and configure Mod_rewrite for Apache on CentOS 7

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

How to 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.

Add or uncomment the following line:

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

Enable and Configure mod_rewrite for Apache on CentOS 7

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.

Add or uncomment the following line:

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

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 and change AllowOverride None to AllowOverride All .

Now restart Apache to put the change into effect:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.

How to Configure mod_rewrite for Apache on CentOS 7

Before following this tutorial, make sure you have a regular, non-root user with sudo privileges.

Installing Apache

We will install Apache using yum , the default package management utility for CentOS.
When prompted with Is this ok [y/d/N]: message, type Y and press the ENTER key to authorize the installation.

Next, start the Apache daemon, a standalone process that creates a pool of child processes or threads to handle requests, with the systemctl utility:
To make sure Apache successfully started, check its state with the status command:

With Apache up and running, let’s turn our attention to its modules.

Verifying mod_rewrite

As of CentOS version 7, the mod_rewrite Apache module is enabled by default. We will verify this is the case with the httpd command and -M flag, which prints a list of all loaded modules:

If the rewrite_module does not appear in the output, enable it by editing the 00-base.conf file with the vi editor:
Once the text file opens type i to enter insert mode and then add or uncomment the highlighted line below:

Now press ESC to leave insert mode. Then, type 😡 then press the ENTER key to save and exit the file.
Next, apply the configuration change by restarting Apache:
With Apache installed and the mod_rewrite module enabled, we’re ready to configure the use of a

Setting up a .htaccess File

Save and exit the file and then restart Apache to apply the change:
Next, create a .htaccess file in the default document root, /var/www/html , for Apache.
Add the following line to the top of the file to activate the RewriteEngine , which instructs Apache to process any rules that follow:

Save and exit the file.

You now have a .htaccess file that will let you define rules to manipulate URLs as needed. Before we get into writing actual rules, let’s take a moment to review the basic mod_rewrite syntax.

Exploring the RewriteRule Syntax

The RewriteRule directive allows us to remap request to Apache based off of the URL. A .htaccess file can house more than one rewrite rule, but at run-time Apache applies the rules in their defined order. A rewrite rule consists of the following structure:

  • RewriteRule: specifies the RewriteRule directive
  • Pattern: a PCRE (Perl Compatible Regular Expression) that matches the desired string.
  • Substitution: where should the matching requests be sent
  • [Flags]: optional parameters to modify the rule.

Exploring the RewriteCond Syntax

The RewriteCond directive allows us to add conditions to a rewrite rule. A rewrite condition consists of the following structure:

  • RewriteCond: specifies the RewriteCond directive
  • TestString: a string to test against
  • Condition: a pattern to match
  • [Flags]: optional parameter to modify the condition.

Setting up Files

Save and exit the file.

In a web browser, navigate to the following address:

You should see a white page with About Us on it. If you remove the .html from the address bar and reload the page, you’ll receive a 404 Not Found error. Apache can only access components by their full filename, but we can alter that with a rewrite rule.

Setting up a RewriteRule

We would like visitors to the About Us page to access it without having to type .html . To accomplish this, we’ll create a rule.

Open the .htaccess file:
After the RewriteEngine On line, add the following:

Save and exit the file.

Visitors can now access the About Us page with the http:// server_domain_or_IP /about URL.
Let’s examine the rewrite rule:

  • ^ indicates the start of the URL, after server_domain_or_IP / is stripped away.
  • & means the end of the URL
  • serverdomainor_IP /about
  • serverdomainor_IP /About
  • serverdomainor_IP /ABOUT

Common Patterns

Now that we have a basic understanding of rewrite rules, we will explore two additional examples in this section.

Example files can be set up, but this tutorial does not include creating them; just the rewrite rules themselves.

Example 1: Simplifying Query Strings with a RewriteRule

Web applications often make use of query strings, which are appended to a URL using the question mark character ( ? ) and delimited by the ampersand character ( & ). Apache ignores these two characters when matching rewrite rules. However, sometimes query strings may be required for passing data between pages.

For example, the URL for a search result page written in PHP may look like this:

Instead, we would like our visitors to be able to use the following cleaner URL:

We can achieve these results in one of two ways — through a simple replacement or matching options.

Example 1A: Simple Replacement

We’ll create a rewrite rule that performs a simple replacement, simplifying a long query URL:

The rule maps shoes/women to results.php?item=shoes&type=women .

Example 1B: Matching Options

  • Specify a series of options using the vertical pipe | , the Boolean «OR» operator
  • Group the match using () , then reference the group using the $1 variable, with 1 for the first matched group

The rule shown above matches a URL of shoes/ followed by a specified type. This will modify the original URL so that:

This matching option allows Apache to evaluate several patterns without having to create a separate rewrite rule for each one.

Example 1C: Matching Character Sets

  • Write a regular expression that matches all alphanumeric characters. The bracket expression [ ] matches any character inside of it, and the + matches any number of characters specified in the brackets
  • Group the match, and reference it with $2 as the second variable in the file

The above example will convert:
to:

We successfully expanded the matching ability to include multiple aspects of a URL.

Example 1D: Passing Query Strings
This section doesn’t introduce any new concepts but addresses an issue that may come up. Using the above example, say we would like to redirect http://example.com/pants/men but will pass an additional query string ?page=2 . We would like to map the following URL:

If you were to attempt to access the above URL with our current settings, you would find that the query string page=2 gets lost. This is easily fixed using an additional QSA flag, which causes the query strings to be combined. Modifying the rewrite rule to match the following will achieve the desired behavior.

Example 2: Adding Conditions with Logic

Now we’re going to look at the use of the RewriteCond directive. If a rewrite condition evaluates to true, then Apache considers the RewriteRule that follows it.

Example 2A: Default Page
Previously, we saw Apache handle a request for an invalid URL by delivering a 404 Not Found page. However, instead of an error page, we would like all malformed URLs redirected back to the homepage. Using a condition, we can check if the requested file exists.

This will redirect something like /admin/ random_text to /admin/home .

  • % checks the requested string
  • !-f the ! or not operator states that if the requested filename does not exist, then execute the following rewrite rule.
  • RewriteRule redirects the requests back to /admin/home

This redirects any request that results in an HTTP 404 response to the error.html page.

Example 2B: IP Address Restriction

A RewriteCond can be used to allow access to a site by a specific IP address.

This example blocks traffic from everywhere except 198.51.100.24.

The entire rule states that if the IP address requesting resources is not 198.51.100.24, then do not allow access.

  • % is the address string
  • !^(198\.51\.100\.24)$ negates the IP address. The \ backslashes escape the . dot, because otherwise, they serve as metacharacters used to match any character.
  • The F flag forbids access, and the L flag indicates that this is the last rule to run, if executed.

Though you can use other methods to block or allow traffic to your site, setting up the restriction in a .htaccess file is the easiest way to achieve these results.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *