Added mod_rewrite for nginx module
This commit is contained in:
73
cms/simple/.htaccess
Normal file
73
cms/simple/.htaccess
Normal file
@@ -0,0 +1,73 @@
|
||||
# ============================================================
|
||||
# .htaccess - Тесты Apache mod_rewrite для nginx
|
||||
# ============================================================
|
||||
# Этот файл содержит правила mod_rewrite для тестирования функционала
|
||||
# модуля ngx_http_apache_rewrite_module в nginx, аналогичного Apache mod_rewrite
|
||||
|
||||
# ============================================================
|
||||
# 1. Перенаправление файлов с расширением .xmx на index.html
|
||||
# ============================================================
|
||||
# Правиство перенаправляет ВСЕ файлы заканчивающиеся на .xmx
|
||||
# на страницу index.html (внешнее перенаправление)
|
||||
|
||||
RewriteEngine On
|
||||
RewriteRule \.xmx$ /index.html [R=301,L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/test.xmx → 301 redirect to /index.html
|
||||
# - http://localhost/test/subdir/file.xmx → 301 redirect to /index.html
|
||||
|
||||
# ============================================================
|
||||
# 2. Блокировка доступа к stop.html (403 Forbidden)
|
||||
# ============================================================
|
||||
# Правиство запрещает доступ к файлу stop.html, возвращая ошибку 403
|
||||
|
||||
RewriteCond %{REQUEST_FILENAME} stop.html$
|
||||
RewriteRule ^ - [F,L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/stop.html → 403 Forbidden (доступ запрещен)
|
||||
|
||||
# ============================================================
|
||||
# 3. Внутреннее перенаправление redirect.html на show.html
|
||||
# ============================================================
|
||||
# Правиство скрывает redirect.html и показывает вместо него show.html
|
||||
# Это внутренняя переадресация (без изменения URL в браузере)
|
||||
|
||||
RewriteRule ^redirect\.html$ show.html [L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/redirect.html → показывает содержимое show.html
|
||||
# - URL остается /test/redirect.html, но показывается content из show.html
|
||||
|
||||
# ============================================================
|
||||
# 4. Перенаправление подкаталога subdir на index.html
|
||||
# ============================================================
|
||||
# При обращении к подкаталогу redirect его на главную страницу
|
||||
|
||||
RewriteRule ^subdir/?$ /index.html [L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/subdir/ → показывает index.html
|
||||
|
||||
# ============================================================
|
||||
# 5. Блокировка доступа ко всем .xmx файлам (кроме test.xmx)
|
||||
# ============================================================
|
||||
# Дополнительно блокируем все файлы с расширением xmx кроме test.xmx
|
||||
# Это демонстрирует условные правила с RewriteCond
|
||||
|
||||
RewriteCond %{REQUEST_FILENAME} !test\.xmx$
|
||||
RewriteRule \.xmx$ - [F,L]
|
||||
|
||||
# Примечание: это правило будет работать ПОСЛЕ первого правила перенаправления
|
||||
# поэтому test.xmx сначала перенаправляется на index.html, а затем блокируется
|
||||
|
||||
# ============================================================
|
||||
# 6. Переопределение статуса ответа (403 Forbidden) для subdir
|
||||
# ============================================================
|
||||
# При обращении к подкаталогу возвращаем ошибку 403 вместо 200 OK
|
||||
|
||||
#RewriteRule ^subdir/?$ - [F,L]
|
||||
|
||||
# Примечание: это правило будет работать ПОСЛЕ правила 4, поэтому subdir
|
||||
# сначала будет переадресован на index.html, а затем заблокирован
|
||||
127
cms/simple/README.md
Normal file
127
cms/simple/README.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# Тесты Apache mod_rewrite для nginx
|
||||
|
||||
## Обзор
|
||||
|
||||
Этот каталог содержит тестовые файлы и правила `.htaccess` для проверки функционала модуля `ngx_http_apache_rewrite_module` в nginx, который обеспечивает совместимость с Apache mod_rewrite.
|
||||
|
||||
## Файлы
|
||||
|
||||
| Файл | Назначение |
|
||||
|------|------------|
|
||||
| `index.html` | Главная страница - назначение для перенаправления .xmx файлов |
|
||||
| `stop.html` | Заблокированная страница (должен возвращать 403) |
|
||||
| `redirect.html` | Внутреннее перенаправление на show.html (URL не меняется) |
|
||||
| `show.html` | Показывается вместо redirect.html при внутреннем rewrite |
|
||||
| `test.xmx` | Тестовый файл для проверки правила перенаправления .xmx расширения |
|
||||
|
||||
## Правила .htaccess
|
||||
|
||||
### 1. Перенаделение файлов с расширением `.xmx` на index.html
|
||||
|
||||
```apache
|
||||
RewriteRule \.xmx$ /index.html [R=301,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- Запрос `http://localhost/test/test.xmx` → **301 Redirect** к `/test/index.html`
|
||||
- URL в браузере изменится на `/test/index.html`
|
||||
|
||||
### 2. Блокировка доступа к stop.html (403 Forbidden)
|
||||
|
||||
```apache
|
||||
RewriteCond %{REQUEST_FILENAME} =stop.html
|
||||
RewriteRule ^ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- Запрос `http://localhost/test/stop.html` → **403 Forbidden** ("Доступ запрещен")
|
||||
- Страница не будет отображаться
|
||||
|
||||
### 3. Внутреннее перенаправление redirect.html на show.html
|
||||
|
||||
```apache
|
||||
RewriteRule ^redirect\.html$ show.html [L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- Запрос `http://localhost/test/redirect.html` → **показывается содержимое show.html**
|
||||
- URL в браузере остается `/test/redirect.html` (не происходит перенаправления)
|
||||
|
||||
### 4. Перенаделение подкаталога subdir на index.html
|
||||
|
||||
```apache
|
||||
RewriteRule ^subdir/?$ /index.html [L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- Запрос `http://localhost/test/subdir/` → **показывается index.html**
|
||||
- URL в браузере остается `/test/subdir/`
|
||||
|
||||
### 5. Дополнительные проверки
|
||||
|
||||
- Флаг `[L]` (Last) - останавливает обработку правил после выполнения
|
||||
- Флаг `[F]` (Forbidden) - возвращает ошибку 403 Forbidden
|
||||
- Флаг `[R=301]` - внешнее перенаправление с кодом статуса 301 Moved Permanently
|
||||
|
||||
## Порядок применения правил
|
||||
|
||||
В модуле nginx приоритет следующий:
|
||||
|
||||
1. **Правила из .htaccess** (высокий приоритет)
|
||||
2. **Правила из nginx конфигурации** (низкий приоритет)
|
||||
|
||||
При наличии флага `[END]` в правилах .htaccess, дальнейшая обработка всех правил останавливается.
|
||||
|
||||
## Поддержка флагоv mod_rewrite
|
||||
|
||||
| Флаг | Значение | Описание |
|
||||
|------|----------|----------|
|
||||
| `L` | Last | Остановить обработку остальных правил |
|
||||
| `F` | Forbidden | Заблокировать доступ (403) |
|
||||
| `R=301` | Redirect | Внешнее перенаправление с кодом 301 |
|
||||
| `END` | End | Полностью остановить обработку rewrite |
|
||||
|
||||
## Примеры запросов для тестирования
|
||||
|
||||
```bash
|
||||
# Перенаделение .xmx файла на index.html
|
||||
curl -I http://localhost/test/test.xmx
|
||||
# Ожидаемый ответ: HTTP/1.1 301 Moved Permanently
|
||||
# Location: /test/index.html
|
||||
|
||||
# Блокировка stop.html
|
||||
curl -I http://localhost/test/stop.html
|
||||
# Ожидаемый ответ: HTTP/1.1 403 Forbidden
|
||||
|
||||
# Внутреннее перенаправление redirect.html на show.html
|
||||
curl -I http://localhost/test/redirect.html
|
||||
# Ожидаемый ответ: HTTP/1.1 200 OK (content из show.html)
|
||||
|
||||
# Перенаделение subdir на index.html
|
||||
curl -I http://localhost/test/subdir/
|
||||
# Ожидаемый ответ: HTTP/1.1 200 OK (content из index.html)
|
||||
```
|
||||
|
||||
## Установка и запуск
|
||||
|
||||
Для запуска тестов потребуется:
|
||||
|
||||
1. Скомпилированный nginx с модулем `ngx_http_apache_rewrite_module`
|
||||
2. Конфигурация nginx, указывающая каталог `test/` как корень сайта
|
||||
3. Активированный флаг `.htaccess` через директиву `HtAccess on`
|
||||
|
||||
Пример конфигурации:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
location /test {
|
||||
root /workspaces/test1/test;
|
||||
|
||||
HtAccess on;
|
||||
HtAccessFile .htaccess;
|
||||
}
|
||||
}
|
||||
```
|
||||
311
cms/simple/SUMMARY.md
Normal file
311
cms/simple/SUMMARY.md
Normal file
@@ -0,0 +1,311 @@
|
||||
# Тесты Apache mod_rewrite для nginx - ПОЛНАЯ СУММАРИЯ
|
||||
|
||||
## 📁 Структура тестовых файлов
|
||||
|
||||
```
|
||||
/test1/test/
|
||||
├── .htaccess # Главное правило rewrite для корневого каталога
|
||||
├── index.html # Главная страница (назначение для redirect)
|
||||
├── show.html # Показывается вместо redirect.html
|
||||
├── stop.html # Блокируется (403 Forbidden)
|
||||
├── redirect.html # Внутреннее перенаправление на show.html
|
||||
├── test.xmx # Файл .xmx для тестирования расширения
|
||||
├── README.md # Документация по тестам
|
||||
├── SUMMARY.md # Эта страница - полная суммари
|
||||
└── subdir/ # Подкаталог с дополнительными тестами
|
||||
├── .htaccess # Правила rewrite для подкаталога
|
||||
├── file.html # Файл в подкаталоге
|
||||
└── other.xmx # Другой файл .xmx (блокируется)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔥 Ключевые правила .htaccess
|
||||
|
||||
### 1️⃣ Перенаделение файлов с расширением `.xmx` на index.html
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteRule \.xmx$ /index.html [R=301,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/test.xmx` | 301 Redirect → `/test/index.html` |
|
||||
| URL в браузере меняется на `/test/index.html` | ✅ Внешнее перенаправление |
|
||||
|
||||
**Логика:**
|
||||
- Все файлы заканчивающиеся на `.xmx` перенаправляются на главную страницу
|
||||
- Используется флаг `[R=301]` для внешнего HTTP redirect
|
||||
- Флаг `[L]` останавливает дальнейшую обработку правил
|
||||
|
||||
---
|
||||
|
||||
### 2️⃣ Блокировка доступа к stop.html (403 Forbidden)
|
||||
|
||||
**Правила:**
|
||||
```apache
|
||||
RewriteCond %{REQUEST_FILENAME} =stop.html
|
||||
RewriteRule ^ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/stop.html` | 403 Forbidden (Доступ запрещен) |
|
||||
| Страница не отображается | ✅ Полная блокировка |
|
||||
|
||||
**Логика:**
|
||||
- `RewriteCond` проверяет что запрос именно к stop.html
|
||||
- `RewriteRule ^ - [F]` возвращает ошибку 403 Forbidden
|
||||
- Флаг `[L]` останавливает обработку
|
||||
|
||||
---
|
||||
|
||||
### 3️⃣ Внутреннее перенаправление redirect.html на show.html
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteRule ^redirect\.html$ show.html [L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/redirect.html` | Показывается content из show.html |
|
||||
| URL в браузере остается `/test/redirect.html` | ✅ Internal rewrite |
|
||||
|
||||
**Логика:**
|
||||
- Правило скрывает redirect.html и показывает вместо него show.html
|
||||
- Происходит внутренняя переадресация без изменения URL
|
||||
- Флаг `[L]` останавливает обработку
|
||||
|
||||
---
|
||||
|
||||
### 4️⃣ Перенаделение подкаталога subdir на index.html
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteRule ^subdir/?$ /index.html [L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/subdir/` | Показывается content из index.html |
|
||||
| URL в браузере остается `/test/subdir/` | ✅ Internal rewrite |
|
||||
|
||||
---
|
||||
|
||||
### 5️⃣ Дополнительные проверки (из main .htaccess)
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteCond %{REQUEST_FILENAME} !test\.xmx$
|
||||
RewriteRule \.xmx$ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- Блокирует все `.xmx` файлы кроме test.xmx
|
||||
- **НО:** Работает ПОСЛЕ правила 1, поэтому test.xmx сначала редиректится на index.html
|
||||
|
||||
---
|
||||
|
||||
### 6️⃣ Перенаделение subdir с последующей блокировкой (конфликт)
|
||||
|
||||
**Порядок в .htaccess:**
|
||||
```apache
|
||||
# Сначала перенаправление
|
||||
RewriteRule ^subdir/?$ /index.html [L]
|
||||
|
||||
# Затем блокировка
|
||||
RewriteRule ^subdir/?$ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
- subdir сначала переадресуется на index.html (правило 4)
|
||||
- Затем применяется правило блокировки → 403 Forbidden
|
||||
- **Итог:** subdir заблокирован с ошибкой 403
|
||||
|
||||
---
|
||||
|
||||
## 📁 Правила в подкаталоге `subdir/.htaccess`
|
||||
|
||||
### 1️⃣ Блокировка всех .xmx файлов в subdir (кроме test.xmx)
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteRule \.xmx$ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/subdir/other.xmx` | 403 Forbidden |
|
||||
| Файл заблокирован | ✅ |
|
||||
|
||||
---
|
||||
|
||||
### 2️⃣ Внутреннее перенаправление subdir/file.html на ../show.html
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteRule ^file\.html$ ../show.html [L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/subdir/file.html` | Показывается content из show.html (в родительском каталоге) |
|
||||
| URL остается `/test/subdir/file.html` | ✅ Internal rewrite с относительным путем |
|
||||
|
||||
---
|
||||
|
||||
### 3️⃣ Блокировка всех файлов кроме .html в subdir
|
||||
|
||||
**Правило:**
|
||||
```apache
|
||||
RewriteCond %{REQUEST_FILENAME} !-ext=html
|
||||
RewriteRule ^ - [F,L]
|
||||
```
|
||||
|
||||
**Ожидаемое поведение:**
|
||||
| Запрос | Результат |
|
||||
|--------|-----------|
|
||||
| `http://localhost/test/subdir/file.txt` | 403 Forbidden |
|
||||
| Только .html файлы доступны | ✅ Фильтрация по расширению |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Тестирование функционала mod_rewrite
|
||||
|
||||
### Поддерживаемые флаги:
|
||||
|
||||
| Флаг | Значение | Описание |
|
||||
|------|----------|----------|
|
||||
| `L` | Last | Остановить обработку остальных правил в .htaccess |
|
||||
| `F` | Forbidden | Возвращать ошибку 403 Forbidden |
|
||||
| `R=301` | Redirect | Внешнее перенаправление с кодом HTTP 301 Moved Permanently |
|
||||
| `END` | End | Остановить ВСЮ обработку rewrite (включая nginx config rules) |
|
||||
|
||||
### Поддерживаемые директивы:
|
||||
|
||||
| Директива | Описание |
|
||||
|-----------|----------|
|
||||
| `RewriteEngine on/off` | Включение/выключение mod_rewrite для .htaccess |
|
||||
| `RewriteRule pattern substitution [flags]` | Правило перенаправления |
|
||||
| `RewriteCond test string` | Условие для правила RewriteRule |
|
||||
|
||||
---
|
||||
|
||||
## 📊 Механизм приоритета
|
||||
|
||||
### Порядок применения правил:
|
||||
|
||||
```
|
||||
┌───────────────────────────────┐
|
||||
│ 1. Правила из .htaccess │ ← Higher Priority
|
||||
│ ├─ Read & parse │
|
||||
│ ├─ Convert to mod_rewrite │
|
||||
│ └─ Apply rules │
|
||||
│ │
|
||||
├───────────────────────────────┤
|
||||
│ Check END flag │
|
||||
│ if (ctx->end) STOP ALL │ ← Blocks nginx config!
|
||||
├───────────────────────────────┤
|
||||
│ 2. Правила из nginx config │ ← Lower Priority
|
||||
│ └─ Apply from server/loc │
|
||||
└───────────────────────────────┘
|
||||
```
|
||||
|
||||
**Ключевой момент:**
|
||||
- При наличии флага `[END]` в .htaccess, обработка ВСЕХ правил rewrite останавливается
|
||||
- Это позволяет полностью блокировать nginx config rules при необходимости
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Примеры CURL запросов для тестирования
|
||||
|
||||
```bash
|
||||
# 1. Перенаправление .xmx на index.html (301)
|
||||
curl -I http://localhost/test/test.xmx
|
||||
# Ожидаемый: HTTP/1.1 301 Moved Permanently
|
||||
# Location: /test/index.html
|
||||
|
||||
# 2. Блокировка stop.html (403)
|
||||
curl -I http://localhost/test/stop.html
|
||||
# Ожидаемый: HTTP/1.1 403 Forbidden
|
||||
|
||||
# 3. Internal rewrite redirect.html → show.html (200 OK, content из show.html)
|
||||
curl -s http://localhost/test/redirect.html | grep h1
|
||||
# Ожидаемый: <h1>show.html</h1>
|
||||
|
||||
# 4. Internal rewrite subdir → index.html (200 OK)
|
||||
curl -I http://localhost/test/subdir/
|
||||
# Ожидаемый: HTTP/1.1 200 OK
|
||||
|
||||
# 5. Блокировка other.xmx в subdir (403)
|
||||
curl -I http://localhost/test/subdir/other.xmx
|
||||
# Ожидаемый: HTTP/1.1 403 Forbidden
|
||||
|
||||
# 6. Internal rewrite subdir/file.html → ../show.html (200 OK)
|
||||
curl -s http://localhost/test/subdir/file.html | grep h1
|
||||
# Ожидаемый: <h1>show.html</h1>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 Установка и запуск тестов
|
||||
|
||||
### Конфигурация nginx для запуска тестов:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
# Корневой сайт
|
||||
location / {
|
||||
root /workspaces/test1/nginx-1.25.3/html;
|
||||
}
|
||||
|
||||
# Тестовый каталог с .htaccess поддержкой
|
||||
location /test {
|
||||
alias /workspaces/test1/test/;
|
||||
|
||||
HtAccess on; # Включить чтение .htaccess файлов
|
||||
HtAccessFile .htaccess; # Файл конфигурации
|
||||
|
||||
# Для подкаталога subdir (авто-поиск .htaccess)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Команды запуска:
|
||||
|
||||
```bash
|
||||
# 1. Скомпилировать nginx с модулем mod_rewrite
|
||||
cd /workspaces/test1/nginx-1.25.3 && make modules
|
||||
|
||||
# 2. Запустить nginx
|
||||
./nginx -c /path/to/nginx.conf
|
||||
|
||||
# 3. Тестировать правила через curl или браузер
|
||||
curl http://localhost/test/redirect.html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Итог
|
||||
|
||||
Модуль `ngx_http_apache_rewrite_module` обеспечивает:
|
||||
|
||||
1. ✅ **Чтение .htaccess файлов** при каждом запросе с проверкой mtime
|
||||
2. ✅ **Кэширование директив** в памяти на время жизненного цикла запроса
|
||||
3. ✅ **Конвертацию Apache mod_rewrite правил** в формат nginx mod_rewrite
|
||||
4. ✅ **Приоритет .htaccess выше nginx config rules**
|
||||
5. ✅ **Флаг [END] для полной остановки обработки rewrite**
|
||||
6. ✅ **Поддержка флагоv L, F, R=301, END**
|
||||
|
||||
Все тестовые файлы готовы и содержат документацию по ожидаемому поведению! 🎉
|
||||
40
cms/simple/index.html
Normal file
40
cms/simple/index.html
Normal file
@@ -0,0 +1,40 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Index - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>index.html</h1>
|
||||
<p>Вы попали на index.html.</p>
|
||||
<p>
|
||||
<strong
|
||||
>Это страница назначения при перенаправлении файлов с
|
||||
расширением xmx.</strong
|
||||
>
|
||||
</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="show.html">Показать (show.html)</a></li>
|
||||
<li><a href="stop.html">Stop - заблокированная страница</a></li>
|
||||
<li>
|
||||
<a href="redirect.html">Redirect - редирект на show.html</a>
|
||||
</li>
|
||||
<li><a href="subdir/">Подкаталог</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p><em>Тесты mod_rewrite для nginx:</em></p>
|
||||
<ol>
|
||||
<li>
|
||||
Запросите <code>.xmx</code> файл → перенаправление на index.html
|
||||
</li>
|
||||
<li>
|
||||
Запросите <code>stop.html</code> → 403 Forbidden (доступ
|
||||
запрещен)
|
||||
</li>
|
||||
<li>Запросите <code>redirect.html</code> → покажет show.html</li>
|
||||
</ol>
|
||||
</body>
|
||||
</html>
|
||||
159
cms/simple/nginx.conf
Normal file
159
cms/simple/nginx.conf
Normal file
@@ -0,0 +1,159 @@
|
||||
|
||||
load_module modules/ngx_http_apache_rewrite_module.so;
|
||||
worker_processes 1;
|
||||
|
||||
error_log logs/error.log debug;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
sendfile on;
|
||||
|
||||
keepalive_timeout 65;
|
||||
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name localhost;
|
||||
|
||||
|
||||
location / {
|
||||
root html;
|
||||
index index.html index.htm;
|
||||
}
|
||||
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root html;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name example1.com;
|
||||
|
||||
root /sites/site1;
|
||||
|
||||
HtaccessEnable on;
|
||||
|
||||
RewriteEngine On;
|
||||
|
||||
location / {
|
||||
RewriteEngine On;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name example2.com;
|
||||
|
||||
root /sites/site2;
|
||||
|
||||
HtaccessEnable on;
|
||||
|
||||
RewriteEngine On;
|
||||
index index.php;
|
||||
|
||||
location / {
|
||||
RewriteEngine On;
|
||||
autoindex on;
|
||||
}
|
||||
|
||||
location ~* \.php$ {
|
||||
RewriteEngine On;
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^(.+\.php)(/.+)$;
|
||||
fastcgi_pass unix:/run/php-fpm/www.sock;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name example3.com;
|
||||
|
||||
root /sites/site3;
|
||||
|
||||
HtaccessEnable on;
|
||||
|
||||
RewriteEngine On;
|
||||
index index.php;
|
||||
|
||||
location / {
|
||||
RewriteEngine On;
|
||||
autoindex on;
|
||||
}
|
||||
|
||||
location ~* \.php$ {
|
||||
RewriteEngine On;
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^(.+\.php)(/.+)$;
|
||||
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name example4.com;
|
||||
|
||||
root /sites/site4;
|
||||
|
||||
HtaccessEnable on;
|
||||
|
||||
RewriteEngine On;
|
||||
index index.php;
|
||||
|
||||
location / {
|
||||
RewriteEngine On;
|
||||
autoindex on;
|
||||
}
|
||||
|
||||
location ~* \.php$ {
|
||||
RewriteEngine On;
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^(.+\.php)(/.+)$;
|
||||
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8081;
|
||||
server_name example5.com;
|
||||
|
||||
root /sites/site5;
|
||||
|
||||
HtaccessEnable on;
|
||||
|
||||
RewriteEngine On;
|
||||
index index.php;
|
||||
|
||||
location / {
|
||||
RewriteEngine On;
|
||||
autoindex on;
|
||||
}
|
||||
|
||||
location ~* \.php$ {
|
||||
RewriteEngine On;
|
||||
include fastcgi_params;
|
||||
fastcgi_split_path_info ^(.+\.php)(/.+)$;
|
||||
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
26
cms/simple/redirect.html
Normal file
26
cms/simple/redirect.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Redirect - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>redirect.html</h1>
|
||||
<p>Вы попали на redirect.html.</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="index.html">На главную (index.html)</a></li>
|
||||
<li><a href="show.html">Показать (show.html)</a></li>
|
||||
<li><a href="stop.html">Stop - заблокированная</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p>
|
||||
<em><strong style="color: green;">Эта страница должна быть скрыта!</strong></em>
|
||||
</p>
|
||||
<p>
|
||||
При обращении к redirect.html, mod_rewrite должен показать show.html вместо этой страницы.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
26
cms/simple/show.html
Normal file
26
cms/simple/show.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Show - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>show.html</h1>
|
||||
<p>Вы попали на show.html.</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="index.html">На главную (index.html)</a></li>
|
||||
<li><a href="redirect.html">Redirect - перенаправляет сюда</a></li>
|
||||
<li><a href="stop.html">Stop - заблокированная</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p>
|
||||
<em><strong style="color: green;">Показано вместо redirect.html!</strong></em>
|
||||
</p>
|
||||
<p>
|
||||
Это страница-назначение для правила <code>RewriteRule ^redirect\.html$ show.html [L]</code>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
10
cms/simple/site1.conf
Normal file
10
cms/simple/site1.conf
Normal file
@@ -0,0 +1,10 @@
|
||||
<VirtualHost 192.168.3.96:80>
|
||||
DocumentRoot "/sites/site1"
|
||||
ServerName example1.com
|
||||
|
||||
<Directory /sites/site1>
|
||||
Options +Indexes +FollowSymLinks
|
||||
AllowOverride All
|
||||
Require all granted
|
||||
</Directory>
|
||||
</VirtualHost>
|
||||
0
cms/simple/somedir/.gitkeep
Normal file
0
cms/simple/somedir/.gitkeep
Normal file
23
cms/simple/stop.html
Normal file
23
cms/simple/stop.html
Normal file
@@ -0,0 +1,23 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Stop - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>stop.html</h1>
|
||||
<p>Вы попали на stop.html.</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="index.html">На главную (index.html)</a></li>
|
||||
<li><a href="show.html">Показать (show.html)</a></li>
|
||||
<li><a href="redirect.html">Redirect</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p>
|
||||
<em><strong style="color: red;">Эта страница должна быть заблокирована!</strong></em>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
0
cms/simple/subdir/.gitkeep
Normal file
0
cms/simple/subdir/.gitkeep
Normal file
30
cms/simple/subdir/.htaccess
Normal file
30
cms/simple/subdir/.htaccess
Normal file
@@ -0,0 +1,30 @@
|
||||
# ============================================================
|
||||
# .htaccess в подкаталоге subdir - Тесты mod_rewrite для nginx
|
||||
# ============================================================
|
||||
# Этот файл проверяет работу правил для конкретного location (подкаталога)
|
||||
|
||||
RewriteEngine On
|
||||
|
||||
# Правило 1: Все запросы к файлам с расширением xmx в этом подкаталоге
|
||||
# должны блокироваться с ошибкой 403 Forbidden
|
||||
|
||||
RewriteRule \.xmx$ - [F,L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/subdir/other.xmx → 403 Forbidden
|
||||
|
||||
# Правило 2: Внутреннее перенаделение subdir/file.html на ../show.html
|
||||
# (переход из подкаталога в родительский)
|
||||
|
||||
RewriteRule ^file\.html$ ../show.html [L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/subdir/file.html → показывает содержимое show.html
|
||||
|
||||
# Правило 3: Блокировка доступа ко всем файлам кроме .html
|
||||
|
||||
RewriteCond %{REQUEST_URI} !\.html$
|
||||
RewriteRule ^ - [F,L]
|
||||
|
||||
# Тестирование:
|
||||
# - http://localhost/test/subdir/file.txt → 403 Forbidden
|
||||
26
cms/simple/subdir/file.html
Normal file
26
cms/simple/subdir/file.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>File - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>file.html</h1>
|
||||
<p>Вы попали на file.html в подкаталоге subdir.</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="../index.html">На главную (index.html)</a></li>
|
||||
<li><a href="../show.html">Показать (show.html)</a></li>
|
||||
<li><a href="../redirect.html">Redirect</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p>
|
||||
<em><strong style="color: green;">Это страница из подкаталога!</strong></em>
|
||||
</p>
|
||||
<p>
|
||||
При обращении к <code>/test/subdir/file.html</code>, mod_rewrite должен показать содержимое <code>../show.html</code>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
27
cms/simple/subdir/other.xmx
Normal file
27
cms/simple/subdir/other.xmx
Normal file
@@ -0,0 +1,27 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Other XMX - Тест mod_rewrite для nginx</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>other.xmx</h1>
|
||||
<p>Вы попытались получить этот файл.</p>
|
||||
|
||||
<hr />
|
||||
<ul>
|
||||
<li><a href="../index.html">На главную (index.html)</a></li>
|
||||
<li><a href="../show.html">Показать (show.html)</a></li>
|
||||
<li><a href="file.html">File.html</a></li>
|
||||
</ul>
|
||||
|
||||
<hr />
|
||||
<p>
|
||||
<em><strong style="color: red;">Этот файл должен быть заблокирован!</strong></em>
|
||||
</p>
|
||||
<p>
|
||||
При обращении к <code>/test/subdir/other.xmx</code>, mod_rewrite должен вернуть
|
||||
<code style="background-color: #f00; color: white;">403 Forbidden</code>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
26
cms/simple/test.xmx
Normal file
26
cms/simple/test.xmx
Normal file
@@ -0,0 +1,26 @@
|
||||
# Test File - test.xmx
|
||||
|
||||
This is a test file used to verify the mod_rewrite rule that redirects all files ending with .xmx extension to index.html.
|
||||
|
||||
## How it works:
|
||||
|
||||
When you request any `.xmx` file in this directory, the following rule from `.htaccess` will be applied:
|
||||
|
||||
```
|
||||
RewriteRule \.xmx$ /index.html [R=301,L]
|
||||
```
|
||||
|
||||
This redirects your browser to `/index.html`.
|
||||
|
||||
## Test URLs:
|
||||
|
||||
- `http://localhost/test/test.xmx` → redirects to `/test/index.html`
|
||||
- `http://localhost/test/subdir/other.xmx` → redirects to `/test/index.html`
|
||||
- `http://localhost/test/deep/path/file.xmx` → redirects to `/test/index.html`
|
||||
|
||||
## Additional Test Files:
|
||||
|
||||
See other test pages in this directory:
|
||||
- index.html - main page
|
||||
- show.html - shown instead of redirect.html via internal rewrite
|
||||
- stop.html - should be blocked (403 Forbidden) by mod_rewrite rules
|
||||
Reference in New Issue
Block a user