Added mod_rewrite for nginx module

This commit is contained in:
alexey
2026-03-23 01:15:59 +03:00
commit 0d2c6277e1
124 changed files with 11079 additions and 0 deletions

159
cms/wordpress/nginx.conf Normal file
View 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;
}
}
}

16
cms/wordpress/site3.conf Normal file
View File

@@ -0,0 +1,16 @@
<VirtualHost *:80>
DocumentRoot "/sites/site3"
ServerName example3.com
DirectoryIndex index.php
<Directory /sites/site3/wordpress>
Options +Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>

View File

@@ -0,0 +1,140 @@
#!/bin/bash
# ============================================
# WordPress .htaccess Rules Test Script
# ============================================
# This script tests each rule from cms/wordpress/.htaccess
# Assumption: Site root is mapped to /home/alexey/projects/workspace-zed/test1/cms/wordpress
# Domain: test.my.brp
# ============================================
BASE_URL="http://test.my.brp"
echo "=============================================="
echo "WordPress .htaccess Rules Test Suite"
echo "=============================================="
echo ""
# Function to test a rule and report result (status only)
test_rule() {
local description="$1"
local url="$2"
local expected_status="$3" # e.g., 403, 404, 200
echo "--- Test: $description ---"
response=$(curl -s -o /dev/null -w "%{http_code}" "$url")
if [ "$response" = "$expected_status" ]; then
echo "✓ PASS (HTTP $response)"
else
echo "✗ FAIL (Expected: HTTP $expected_status, Got: HTTP $response)"
fi
echo ""
}
# Function to test a rule and verify content contains expected string
test_rule_content() {
local description="$1"
local url="$2"
local headers="$3" # Optional: additional curl -H header flags (can be empty)
local expected_status="$4" # e.g., 403, 404, 200
local expected_content="$5" # Expected substring in response body
echo "--- Test: $description ---"
if [ -n "$headers" ]; then
response=$(curl -s -H "$headers" "$url")
http_code=$(curl -s -H "$headers" -o /dev/null -w "%{http_code}" "$url")
else
response=$(curl -s "$url")
http_code=$(curl -s -o /dev/null -w "%{http_code}" "$url")
fi
# Check status code
if [ "$http_code" != "$expected_status" ]; then
echo "✗ FAIL (Status: HTTP $http_code, Expected: HTTP $expected_status)"
return 1
fi
# Check content contains expected substring
if [[ "$response" == *"$expected_content"* ]]; then
echo "✓ PASS (HTTP $http_code, Content matches '$expected_content')"
else
echo "✗ FAIL (Content missing: '$expected_content') - Response:"
echo "$response" | head -5
fi
echo ""
}
echo "=============================================="
echo "1. HTTP_AUTHORIZATION Header Rewrite Rule"
echo "=============================================="
# Test that Authorization header is properly handled by WordPress REST API mock
# This rule copies HTTP Authorization header to HTTP_AUTHORIZATION env var via mod_rewrite [E=...]
test_rule_content "WordPress REST API: Authorization header passed through mod_rewrite" \
"$BASE_URL/wordpress/wp-json/wp/v2/posts" \
"Authorization: secret_token_123" \
"200" \
"\"status\": \"success\""
# Additional test: verify token verification in response
test_rule_content "WordPress REST API: Token verified correctly" \
"$BASE_URL/wordpress/wp-json/wp/v2/posts" \
"" \
"401" \
"\"message\": \"unauth\""
echo ""
echo "=============================================="
echo "2. RewriteBase Configuration"
echo "=============================================="
# RewriteBase / sets base path to root - verifies routing works correctly
test_rule_content "Base path routing (root directory)" \
"$BASE_URL/wordpress/" \
"" \
"200" \
"WordPress Content Route"
echo ""
echo "=============================================="
echo "3. Direct index.php Access Protection"
echo "=============================================="
# RewriteRule ^index\.php$ - [L] - direct access to index.php should return 200 OK
test_rule_content "Direct index.php access (not rewritten)" \
"$BASE_URL/wordpress/index.php" \
"" \
"200" \
"WordPress Content Route"
echo ""
echo "=============================================="
echo "4. WordPress Core Routing Rules"
echo "=============================================="
# Test non-existing file routes through index.php (!-f condition)
test_rule_content "Non-existing file routing (routes to index.php)" \
"$BASE_URL/wordpress/nonexistent-page/" \
"" \
"200" \
"WordPress Content Route"
# Test existing file access - should return 200 OK (!-f passes for existing files)
test_rule "Existing file access (existing.jpg)" \
"$BASE_URL/wordpress/existing.jpg" \
"200"
# Test non-existing directory routing - should route to index.php (!-d condition)
test_rule_content "Non-existing directory routing (routes to index.php)" \
"$BASE_URL/wordpress/nonexistent-dir/" \
"" \
"200" \
"WordPress Content Route"
# Test existing directory access - should return 200 OK (!-d passes for existing dirs)
test_rule "Existing directory access (somedir/)" \
"$BASE_URL/wordpress/somedir/" \
"200"
echo ""
echo "=============================================="
echo "Test Suite Complete"
echo "=============================================="

View File

@@ -0,0 +1,8 @@
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /wordpress
RewriteRule ^wp-json/(.*)$ wp_api.php?api=$1 [L,QSA]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

View File

@@ -0,0 +1,109 @@
# WordPress .htaccess Test Structure
## Directory Layout Overview
```
/test1/cms/wordpress/
├── existing.jpg - Existing file for routing test (200 OK)
│ - Tests: RewriteRule !-f condition passes for existing files
├── index.php - WordPress entry point
│ - Returns: "WordPress Content Route" page
│ - Used by Rule 3 (direct access protection) and Rule 4 (routing)
├── README.md - This documentation file
├── somedir/ - Existing directory for routing test (200 OK)
│ - Tests: RewriteRule !-d condition passes for existing directories
└── test-wp-rewriterules.sh - Bash script to test all WordPress rules using curl
```
## Apache Rules Explained
### 1. HTTP Authorization Header Passing
```apache
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
```
**Что делает:** Копирует HTTP Authorization header из запроса в переменную `HTTP_AUTHORIZATION` для PHP
**Зачем нужно:** WordPress REST API использует это для аутентификации через Bearer token
**Пример использования:**
```bash
curl -H "Authorization: Bearer secret_token" http://site.com/wp-json/wp/v2/posts
```
### 2. RewriteBase Configuration
```apache
RewriteBase /
```
**Что делает:** Устанавливает базовый путь переписывания к корню сайта
**Зачем нужно:** Определяет контекст для относительных путей в других правилах
### 3. Direct index.php Access Protection
```apache
RewriteRule ^index\.php$ - [L]
```
**Что делает:** Если запрос идёт прямо на `index.php`, ничего не переписывает, останавливает процесс ([L] = Last)
**Зачем нужно:** Предотвращает зацикливание маршрутизации
### 4. WordPress Core Routing
```apache
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
```
**Что делает:**
- `!-f` - проверяет, что запрашиваемый файл НЕ существует
- `!-d` - проверяет, что запрашиваемая директория НЕ существует
- Если оба условия true - маршрутизирует через `/index.php`
**Зачем нужно:** WordPress использует "чистые URL" (permalinks), все запросы на несуществующие файлы/директории рутятся через index.php для обработки WP core
## Test Script Features
The script includes two test functions:
1. `test_rule()` - checks HTTP status code only
2. `test_rule_content()` - checks both status AND response body content
## Test Coverage Summary
### 1. HTTP_AUTHORIZATION Header ✓
- REST API request with Authorization header → **200** + "WordPress Content Route" ✓
### 2. RewriteBase Configuration ✓
- Root directory access → **200** + "WordPress Content Route" ✓
### 3. Direct index.php Access ✓
- `/index.php` direct call → **200** (not rewritten) ✓
### 4. WordPress Core Routing ✓
- Non-existing file routes to `index.php`**200**
- Existing file access (`existing.jpg`) → **200**
- Non-existing directory routes to `index.php`**200**
- Existing directory access (`somedir/`) → **200**
## Run Tests
Execute the test script to verify all rules:
```bash
cd /home/alexey/projects/workspace-zed/test1/cms/wordpress
./test-wp-rewriterules.sh
```
Expected results (all should be **PASS ✓**):
- Authorization header handling: HTTP 200 + content "WordPress Content Route" ✓
- Base path routing: HTTP 200 + content "WordPress Content Route" ✓
- Direct index.php access: HTTP 200 ✓
- Non-existing file routing: HTTP 200 ✓
- Existing file access: HTTP 200 ✓
- Non-existing directory routing: HTTP 200 ✓
- Directory access: HTTP 200 ✓

View File

View File

@@ -0,0 +1,15 @@
<?php
/**
* WordPress - index.php (Test version)
* This file handles routing for non-existing files/directories
*/
// Simulated WordPress response
echo "<html><head><title>WordPress Test Site</title></head><body>";
echo "<h1>WordPress Content Route</h1>";
echo "<p>This page is served by index.php via RewriteRule.</p>";
echo "<div class='wp-config'>WordPress Configuration Loaded</div>";
echo "</body></html>";
// Exit
exit;

View File

View File

@@ -0,0 +1,54 @@
<?php
/**
* WordPress REST API Mock (Test version)
* This file checks if Authorization header is properly passed from mod_rewrite
*/
// Check if Authorization header was received
$auth_header = "";
if (isset($_SERVER["HTTP_AUTHORIZATION"])) {
$auth_header = $_SERVER["HTTP_AUTHORIZATION"];
} else {
// Also check for rewritten env var
$auth_env = getenv("HTTP_AUTHORIZATION");
if ($auth_env !== false && $auth_env !== "") {
$auth_header = $auth_env;
}
}
// Set response headers
header("Content-Type: application/json; charset=UTF-8");
if ($auth_header === "secret_token_123") {
// SUCCESS - Authorization header was properly passed through mod_rewrite
echo json_encode(
[
"status" => "success",
"message" => "Authorization verified",
"token_verified" => true,
"wordpress_config_loaded" => true,
"received_auth_header" => $auth_header,
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES,
);
} else {
// FAIL - Authorization header was not passed through mod_rewrite
http_response_code(401);
echo json_encode(
[
"status" => "error",
"message" => "unauth",
"expected" => "Bearer secret_token_123",
"received" => $auth_header ?: "(not set)",
"test_failed" => true,
"hint" =>
"mod_rewrite [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] is NOT passing header to PHP",
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES,
);
}
exit();