-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-params.htaccess
More file actions
45 lines (40 loc) · 1.78 KB
/
Copy pathquery-params.htaccess
File metadata and controls
45 lines (40 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Query Parameter Handling (Apache / .htaccess)
#
# What this does:
# Demonstrates three query-string strategies during a redirect:
# preserve the original params, strip them, or route based on a
# specific parameter's value. Requires mod_rewrite because decisions
# depend on %{QUERY_STRING}.
#
# When to use it:
# Preserve - keep UTM/tracking params through a URL migration.
# Strip - clean dirty legacy URLs down to a canonical target.
# Route - map old ?id=x style URLs to new clean paths.
#
# Notes:
# By default Apache APPENDS the incoming query string to the target.
# A trailing "?" on the substitution DROPS it. The [QSA] flag merges
# new params with the originals.
RewriteEngine On
# 1) PRESERVE (default behavior). /old?utm_source=x -> /new?utm_source=x
RewriteRule ^old$ /new [R=301,L]
# 2) STRIP the query string. The trailing "?" discards incoming params.
# /messy?sid=abc&ref=y -> /clean
RewriteRule ^messy$ /clean? [R=301,L]
# 3) ROUTE on a specific parameter value.
# /article?id=42 -> /articles/42
RewriteCond %{QUERY_STRING} (?:^|&)id=([^&]+)
RewriteRule ^article$ /articles/%1? [R=301,L]
# Example:
# Before: https://example.com/old?utm_source=newsletter
# After: https://example.com/new?utm_source=newsletter (HTTP 301)
#
# Gotchas:
# - Without a trailing "?", the original query string is re-appended to
# the target - the #2 "strip" case needs that "?" to work.
# - %1 comes from the RewriteCond capture (the id value); $1 would come
# from the RewriteRule pattern. Do not mix them up.
# - The RewriteRule pattern matches the path WITHOUT a leading slash in
# .htaccess context (per-directory), hence ^old$ not ^/old$.
# - Add the [QSA] flag if the target already has its own query string
# and you want to merge rather than replace.