Creating rules in .htaccess

Содержание
Redirect: simple moves
RedirectMatch: patterns
RewriteRule basics
Flags that matter
Order of rules
Testing rules
Common pitfalls

Redirect: simple moves

One page moved to a new address. mod_alias handles it in one line - source first, target second:

Redirect 301 /ru/qa/robot/newline.php /ru/qa/robot/basics/newline.php

Use 301 for permanent moves (link equity passes, browsers cache it) and 302 while experimenting. A cached wrong 301 is painful: browsers remember it long after you fix the file, so test with 302 and flip to 301 when sure.

RedirectMatch: patterns

Plain Redirect matches a URL prefix, which glues the remainder onto the target. To retire a whole tree into one file, anchor a regular expression instead:

RedirectMatch 301 ^/edu/suomen/.*$ /edu/index.php

Without the regex, /edu/suomen/x.php would land on /edu/index.phpx.php. Exact single-address matches work the same way:

RedirectMatch 301 ^/robot/?$ /qa/robot/

The /?$ anchor means subpaths like /robot/basics/ are untouched - only the bare directory redirects.

RewriteRule basics

When the target depends on part of the source, mod_rewrite captures it with parentheses and replays it as $1, $2:

RewriteEngine On RewriteRule ^blog/([0-9]{4})/([a-z-]+)\.php$ /archive/$1/$2/ [R=301,L]

RewriteRule sees the path without the leading slash and without the query string. To keep query parameters, add the QSA flag.

Flags that matter

Order of rules

Apache tries rules top to bottom, and a prefix-hungry rule shadows everything below it. Specific rules go first, catch-alls last:

Redirect 301 /pc/LaTeX.php /latex/man/ RedirectMatch 301 ^/pc/LaTeX/.*$ /latex/index.php

Reversed, the catch-all would swallow /pc/LaTeX.php is not matched by ^/pc/LaTeX/.*$ - but a plain Redirect 301 /pc/LaTeX/ prefix above the specific line would shadow it. Comment the ordering constraint in the file, or the next editor will reorder it back.

Testing rules

Never test in a browser first - the 301 cache lies. Ask for headers:

curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" https://aredel.com/robot/

301 https://aredel.com/qa/robot/

Check the chain, not just the first hop: two redirects in a row double the latency and leak ranking. One hop from old URL to final page is the goal.

Common pitfalls

Keep the same discipline as with code: one rule per move, a comment above non-obvious ones, and a periodic audit of every target.

Article author: Andrei Olegovich

Похожие статьи
Development with PHP
Arrays in PHP
Date and Time in PHP - basics
How to display time of multiple timezones in PHP
How to add variable to url in PHP
json_decode
How to get screen size with PHP
Call function from another file
Premature end of chunk coded message body: closing chunk expected
Generate unique random numbers with PHP
Check your HTTP_USER_AGENT
Compare two dates
OOP
Namespaces in PHP
Comments in PHP
Cookies
PHP sessions
Authentication and Authorization in PHP 8
PHP linters we use
PHP errors: case studies
card_from_db(): banner card from a DB row
PHP versions: history in brief
Creating rules in .htaccess
require, require_once, include, include_once
Deduplication in PHP

Поиск по сайту

Канал @aofeed Чат @aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: