I'm trying to rewrite the below URL but the URLs just don't change, no errors.
Current URL:
https://example.com/test/news/?c=value1&s=value2&id=9876
Expected URL:
https://example.com/test/news/value1/value2
My .htaccess
RewriteEngine On
RewriteRule ^test/news/([^/]*)/([^/]*)$ /test/news/?c=$1&s=$2&id=1 [L]
but I've seen many articles where a url such as example.com/display_article.php?articleId=my-article can be rewritten as example.com/articles/my-article for example with .htaccess
But the important point here (that I think you are missing) is that the URL must already have been changed internally in your application - in all your internal links. It is a common misconception that .htaccess alone can be used to change the format of the URL. Whilst .htaccess is an important part of this, it is only part of it.
Yes, you can implement a redirect in .htaccess to redirect from the old to new URL - and this is essential to preserve SEO (see below), but it is not critical to your application working. If you don't first change the URL in your internal links then:
The "old" URL is still exposed in the HTML source. When a user hovers over or copies the link, they are seeing and copying the "old" URL.
Every time a user clicks one of your internal links they are externally redirected to the "new" URL. This is slow for your users, bad for SEO (you should never link to a URL that is redirected) and bad for your server, as it potentially doubles the number of requests hitting your server (OK, 301s are cached locally).
To quote from #IMSoP's answer to this reference question on the subject:
Rewrite rules don't make ugly URLs pretty, they make pretty URLs ugly
So, once you have changed your internal links to the "new" (expected) format, eg. /test/news/value1/value2 (or should that be /test/news/value1/value2/id or even /test/news/id/value1/value2? See below), then you can do as follows...
RewriteRule ^test/news/([^/]*)/([^/]*)$ /test/news/?c=$1&s=$2&id=1 [L]
This internally rewrites a request from /test/news/<value1>/<value2> to /test/news/?c=<value1>&s=<value2>&id=1. However, there are a couple of issues with this:
/test/news/ is not itself a valid endpoint. This requires further rewriting. Perhaps you are serving a DirectoryIndex document (eg. index.php)? This might appear seamless to you, but this requires an additional internal subrequest and makes the rule dependent on other elements of the config. You should rewrite directly to the file that handles the request. eg. /test/news/index.php?c=<value1>&s=<value2>&id=1 (remember, this is entirely hidden from the user).
You are hardcoding the id=1 parameter? Should every URL have the same id? Or should this be passed in the "new" URL (which is what I would expect)? What does the id represent? If this is critical to the routing of the URL then the id should appear earlier in the URL-path, in case the URL gets accidentally truncated when copy/pasted/shared.
If the id is required then it needs to be passed in the "new" URL. We only have the "new" URL to route the request, so the information can't be hidden.
So, if the "new" URL is now /test/news/<id>/<value1>/<value2> then the rewrite would need to be like this instead:
# Rewrite new URLs to old/actual URL
# "/test/news/<id>/<value1>/<value2>" to "/test/news/?c=<value1>&s=<value2>&id=<id>"
RewriteRule ^test/news/(\d+)/([^/]+)/([^/]+)$ /test/news/?c=$2&s=$3&id=$1 [L]
Then (optionally*1) you can implement an external redirect in order to preserve SEO. This is for search engines that have indexed the "old" URLs or third party inbound links that cannot be updated - these need to be corrected to inform search engines of the change and get the user on the "new" canonical URL having followed an out-of-date inbound link.
(*1 It's not "optional" if you are changing an existing URL, but optional with regards to your application being functional.)
This "redirect" goes before the above rewrite:
# Redirect old URLs to the new "canonical" URL
# "/test/news/?c=<value1>&s=<value2>&id=<id>" to "/test/news/<id>/<value1>/<value2>"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^c=([^&]+)&s=([^&]+)&id=(\d+)
RewriteRule ^test/news/$ /$0%3/%1/%2 [QSD,R=301,L]
The $0 backreference contains the full match from the RewriteRule pattern, ie. test/news/ in this case - this simply saves repetition.
The %1, %2 and %3 backreferences contain the values captured from the preceding condition. ie. the values of the c, s and id URL parameters respectively.
Note that the URL parameters / path segments should not be optional as in your original directive (ie. ([^/]*)). If they are optional and they are omitted, then the resulting URL becomes ambiguous. eg. <value2> becomes <value1> if <value1> is omitted.
Note that the URL parameters must be in the order as stated. If you have a mismatch of "old" URLs with these params in a different order (or even intermixed with other params) then this can be accounted for with additional complexity. (It may be easier to perform this redirect in your server-side script, instead of .htaccess.)
The first condition that checks against the REDIRECT_STATUS environment variable ensures that we only redirect direct requests and not rewritten requests by the later rewrite (which would otherwise result in a redirect loop). An alternative on Apache 2.4 is to use the END flag on the RewriteRule instead.
The QSD flag (Apache 2.4) discards the original query string from the request.
You should test first with a 302 (temporary) redirect to avoid potential caching issues and only change to a 301 (permanent) redirect once you have tested that everything works as intended. 301s are cached persistently by the browser so can make testing problematic.
Summary
Your complete .htaccess file should look something like this:
Options -MultiViews +FollowSymLinks
# If relying on the DirectoryIndex to handle the request
DirectoryIndex index.php
RewriteEngine On
# Redirect old URLs to the new "canonical" URL
# "/test/news/?c=<value1>&s=<value2>&id=<id>" to "/test/news/<id>/<value1>/<value2>"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^c=([^&]+)&s=([^&]+)&id=(\d+)
RewriteRule ^test/news/$ /$0%3/%1/%2 [QSD,R=301,L]
# Rewrite new URLs to old/actual URL
# "/test/news/<id>/<value1>/<value2>" to "/test/news/?c=<value1>&s=<value2>&id=<id>"
RewriteRule ^test/news/(\d+)/([^/]+)/([^/]+)$ /test/news/?c=$2&s=$3&id=$1 [L]
"Pretty links" is an often requested topic, but it is rarely fully explained. mod_rewrite is one way to make "pretty links", but it's complex and its syntax is very terse, hard to grok, and the documentation assumes a certain level of proficiency in HTTP. Can someone explain in simple terms how "pretty links" work and how mod_rewrite can be used to create them?
Other common names, aliases, terms for clean URLs: RESTful URLs, user-friendly URLs, SEO-friendly URLs, slugging, and MVC URLs (probably a misnomer)
To understand what mod_rewrite does you first need to understand how a web server works. A web server responds to HTTP requests. An HTTP request at its most basic level looks like this:
GET /foo/bar.html HTTP/1.1
This is the simple request of a browser to a web server requesting the URL /foo/bar.html from it. It is important to stress that it does not request a file, it requests just some arbitrary URL. The request may also look like this:
GET /foo/bar?baz=42 HTTP/1.1
This is just as valid a request for a URL, and it has more obviously nothing to do with files.
The web server is an application listening on a port, accepting HTTP requests coming in on that port and returning a response. A web server is entirely free to respond to any request in any way it sees fit/in any way you have configured it to respond. This response is not a file, it's an HTTP response which may or may not have anything to do with physical files on any disk. A web server doesn't have to be Apache, there are many other web servers which are all just programs which run persistently and are attached to a port which respond to HTTP requests. You can write one yourself. This paragraph was intended to divorce you from any notion that URLs directly equal files, which is really important to understand. :)
The default configuration of most web servers is to look for a file that matches the URL on the hard disk. If the document root of the server is set to, say, /var/www, it may look whether the file /var/www/foo/bar.html exists and serve it if so. If the file ends in ".php" it will invoke the PHP interpreter and then return the result. All this association is completely configurable; a file doesn't have to end in ".php" for the web server to run it through the PHP interpreter, and the URL doesn't have to match any particular file on disk for something to happen.
mod_rewrite is a way to rewrite the internal request handling. When the web server receives a request for the URL /foo/bar, you can rewrite that URL into something else before the web server will look for a file on disk to match it. Simple example:
RewriteEngine On
RewriteRule /foo/bar /foo/baz
This rule says whenever a request matches "/foo/bar", rewrite it to "/foo/baz". The request will then be handled as if /foo/baz had been requested instead. This can be used for various effects, for example:
RewriteRule (.*) $1.html
This rule matches anything (.*) and captures it ((..)), then rewrites it to append ".html". In other words, if /foo/bar was the requested URL, it will be handled as if /foo/bar.html had been requested. See http://regular-expressions.info for more information about regular expression matching, capturing and replacements.
Another often encountered rule is this:
RewriteRule (.*) index.php?url=$1
This, again, matches anything and rewrites it to the file index.php with the originally requested URL appended in the url query parameter. I.e., for any and all requests coming in, the file index.php is executed and this file will have access to the original request in $_GET['url'], so it can do anything it wants with it.
Primarily you put these rewrite rules into your web server configuration file. Apache also allows* you to put them into a file called .htaccess within your document root (i.e. next to your .php files).
* If allowed by the primary Apache configuration file; it's optional, but often enabled.
What mod_rewrite does not do
mod_rewrite does not magically make all your URLs "pretty". This is a common misunderstanding. If you have this link in your web site:
<a href="/my/ugly/link.php?is=not&very=pretty">
there's nothing mod_rewrite can do to make that pretty. In order to make this a pretty link, you have to:
Change the link to a pretty link:
<a href="/my/pretty/link">
Use mod_rewrite on the server to handle the request to the URL /my/pretty/link using any one of the methods described above.
(One could use mod_substitute in conjunction to transform outgoing HTML pages and their contained links. Though this is usally more effort than just updating your HTML resources.)
There's a lot mod_rewrite can do and very complex matching rules you can create, including chaining several rewrites, proxying requests to a completely different service or machine, returning specific HTTP status codes as responses, redirecting requests etc. It's very powerful and can be used to great good if you understand the fundamental HTTP request-response mechanism. It does not automatically make your links pretty.
See the official documentation for all the possible flags and options.
To expand on deceze's answer, I wanted to provide a few examples and explanation of some other mod_rewrite functionality.
All of the below examples assume that you have already included RewriteEngine On in your .htaccess file.
Rewrite Example
Lets take this example:
RewriteRule ^blog/([0-9]+)/([A-Za-z0-9-\+]+)/?$ /blog/index.php?id=$1&title=$2 [NC,L,QSA]
The rule is split into 4 sections:
RewriteRule - starts the rewrite rule
^blog/([0-9]+)/([A-Za-z0-9-\+]+)/?$ - This is called the pattern, however I'll just refer to it as the left hand side of the rule - what you want to rewrite from
blog/index.php?id=$1&title=$2 - called the substitution, or right hand side of a rewrite rule - what you want to rewrite to
[NC,L,QSA] are flags for the rewrite rule, separated by a comma, which I will explain more on later
The above rewrite would allow you to link to something like /blog/1/foo/ and it would actually load /blog/index.php?id=1&title=foo.
Left hand side of the rule
^ indicates the start of the page name - so it will rewrite example.com/blog/... but not example.com/foo/blog/...
Each set of (…) parentheses represents a regular expression that we can capture as a variable in the right hand side of the rule. In this example:
The first set of brackets - ([0-9]+) - matches a string with a minimum of 1 character in length and with only numeric values (i.e. 0-9). This can be referenced with $1 in the right hand side of the rule
The second set of parentheses matches a string with a minimum of 1 character in length, containing only alphanumeric characters (A-Z, a-z, or 0-9) or - or + (note + is escaped with a backslash as without escaping it this will execute as a regex repetition character). This can be referenced with $2 in the right hand side of the rule
? means that the preceding character is optional, so in this case both /blog/1/foo/ and /blog/1/foo would rewrite to the same place
$ indicates this is the end of the string we want to match
Flags
These are options that are added in square brackets at the end of your rewrite rule to specify certain conditions. Again, there are a lot of different flags which you can read up on in the documentation, but I'll go through some of the more common flags:
NC
The no case flag means that the rewrite rule is case insensitive, so for the example rule above this would mean that both /blog/1/foo/ and /BLOG/1/foo/ (or any variation of this) would be matched.
L
The last flag indicates that this is the last rule that should be processed. This means that if and only if this rule matches, no further rules will be evaluated in the current rewrite processing run. If the rule does not match, all other rules will be tried in order as usual. If you do not set the L flag, all following rules will be applied to the rewritten URL afterwards.
END
Since Apache 2.4 you can also use the [END] flag. A matching rule with it will completely terminate further alias/rewrite processing. (Whereas the [L] flag can oftentimes trigger a second round, for example when rewriting into or out of subdirectories.)
QSA
The query string append flag allows us to pass in extra variables to the specified URL which will get added to the original get parameters. For our example this means that something like /blog/1/foo/?comments=15 would load /blog/index.php?id=1&title=foo&comments=15
R
This flag isn't one I used in the example above, but is one I thought is worth mentioning. This allows you to specify a http redirect, with the option to include a status code (e.g. R=301). For example if you wanted to do a 301 redirect on /myblog/ to /blog/ you would simply write a rule something like this:
RewriteRule ^/myblog/(*.)$ /blog/$1 [R=301,QSA,L]
Rewrite Conditions
Rewrite conditions make rewrites even more powerful, allowing you to specify rewrites for more specific situations. There are a lot of conditions which you can read about in the documentation, but I'll touch on a few common examples and explain them:
# if the host doesn't start with www. then add it and redirect
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This is a very common practice, which will prepend your domain with www. (if it isn't there already) and execute a 301 redirect. For example, loading up http://example.com/blog/ it would redirect you to http://www.example.com/blog/
# if it cant find the image, try find the image on another domain
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ http://www.example.com/$1 [L]
This is slightly less common, but is a good example of a rule that doesn't execute if the filename is a directory or file that exists on the server.
%{REQUEST_URI} \.(jpg|jpeg|gif|png)$ [NC] will only execute the rewrite for files with a file extension of jpg, jpeg, gif or png (case insensitive).
%{REQUEST_FILENAME} !-f will check to see if the file exists on the current server, and only execute the rewrite if it doesn't
%{REQUEST_FILENAME} !-d will check to see if the file exists on the current server, and only execute the rewrite if it doesn't
The rewrite will attempt to load the same file on another domain
References
Stack Overflow has many other great resources to get started:
Serverfault: Everything you ever wanted to know about mod_rewrite
(Keep in mind to remove the slash in ^/ pattern prefixes for .htaccess usage.)
Do's and Dont's in Hidden features of mod_rewrite.
Look through our most popular mod-rewrite questions and answers.
Apache redirecting and remapping guide.
AskApache ultimate .htaccess guide
And the mod-rewrite tag wiki references.
And newcomer-friendly regex overviews even:
Our regex tag wiki for a syntax compendium.
And the short Apache regex summary.
Else regexp.info for easy-to-understand basics.
Oft-used placeholders
.* matches anything, even an empty string. You don't want to use this pattern everywhere, but often in the last fallback rule.
[^/]+ is more often used for path segments. It matches anything but the forward slash.
\d+ only matches numeric strings.
\w+ matches alphanumeric characters. It's basically shorthand for [A-Za-z0-9_].
[\w\-]+ for "slug"-style path segments, using letters, numbers, dash - and _
[\w\-.,]+ adds periods and commas. Prefer an escaped \- dash in […] charclasses.
\. denotes a literal period. Otherwise . outside of […] is placeholder for any symbol.
Each of these placeholders is usually wrapped in (…) parentheses as capture group. And the whole pattern often in ^………$ start + end markers. Quoting "patterns" is optional.
RewriteRules
The following examples are PHP-centric and a bit more incremental, easier to adapt for similar cases.
They're just summaries, often link to more variations or detailed Q&As.
Static mapping /contact, /about
Shortening a few page names to internal file schemes is most simple:
RewriteRule ^contact$ templ/contact.html
RewriteRule ^about$ about.php
Numeric identifiers /object/123
Introducing shortcuts like http://example.com/article/531 to existing PHP scripts is also easy. The numeric placeholder can just be remapped to a $_GET parameter:
RewriteRule ^article/(\d+)$ article-show.php?id=$1
# └───────────────────────────┘
Slug-style placeholders /article/with-some-title-slug
You can easily extend that rule to allow for /article/title-string placeholders:
RewriteRule ^article/([\w-]+)$ article-show.php?title=$1
# └────────────────────────────────┘
Note that your script must be able (or be adapted) to map those titles back to database-ids. RewriteRules alone can't create or guess information out of thin air.
Slugs with numeric prefixes /readable/123-plus-title
Therefore you'll often see mixed /article/529-title-slug paths used in practice:
RewriteRule ^article/(\d+)-([\w-]+)$ article.php?id=$1&title=$2
# └───────────────────────────────┘
Now you could just skip passing the title=$2 anyway, because your script will typically rely on the database-id anyway. The -title-slug has become arbitrary URL decoration.
Uniformity with alternative lists /foo/… /bar/… /baz/…
If you have similar rules for multiple virtual page paths, then you can match and compact them with | alternative lists. And again just reassign them to internal GET parameters:
# ┌─────────────────────────┐
RewriteRule ^(blog|post|user)/(\w+)$ disp.php?type=$1&id=$2
# └───────────────────────────────────┘
You can split them out into individual RewriteRules should this get too complex.
Dispatching related URLs to different backends /date/SWITCH/backend
A more practical use of alternative lists are mapping request paths to distinct scripts. For example to provide uniform URLs for an older and a newer web application based on dates:
# ┌─────────────────────────────┐
# │ ┌───────────┼───────────────┐
RewriteRule ^blog/(2009|2010|2011)/([\d-]+)/?$ old/blog.php?date=$2
RewriteRule ^blog/(\d+)/([\d-]+)/?$ modern/blog/index.php?start=$2
# └──────────────────────────────────────┘
This simply remaps 2009-2011 posts onto one script, and all other years implicitly to another handler.
Note the more specific rule coming first. Each script might use different GET params.
Other delimiters than just / path slashes /user-123-name
You're most commonly seeing RewriteRules to simulate a virtual directory structure. But you're not forced to be uncreative. You can as well use - hyphens for segmenting or structure.
RewriteRule ^user-(\d+)$ show.php?what=user&id=$1
# └──────────────────────────────┘
# This could use `(\w+)` alternatively for user names instead of ids.
For the also common /wiki:section:Page_Name scheme:
RewriteRule ^wiki:(\w+):(\w+)$ wiki.php?sect=$1&page=$2
# └─────┼────────────────────┘ │
# └────────────────────────────┘
Occasionally it's suitable to alternate between /-delimiters and : or . in the same rule even. Or have two RewriteRules again to map variants onto different scripts.
Optional trailing / slash /dir = /dir/
When opting for directory-style paths, you can make it reachable with and without a final /
RewriteRule ^blog/([\w-]+)/?$ blog/show.php?id=$1
# ┗┛
Now this handles both http://example.com/blog/123 and /blog/123/. And the /?$ approach is easy to append onto any other RewriteRule.
Flexible segments for virtual paths .*/.*/.*/.*
Most rules you'll encounter map a constrained set of /…/ resource path segments to individual GET parameters. Some scripts handle a variable number of options however.
The Apache regexp engine doesn't allow optionalizing an arbitrary number of them. But you can easily expand it into a rule block yourself:
Rewriterule ^(\w+)/?$ in.php?a=$1
Rewriterule ^(\w+)/(\w+)/?$ in.php?a=$1&b=$2
Rewriterule ^(\w+)/(\w+)/(\w+)/?$ in.php?a=$1&b=$2&c=$3
# └─────┴─────┴───────────────────┴────┴────┘
If you need up to five path segments, then copy this scheme along into five rules. You can of course use a more specific [^/]+ placeholder each.
Here the ordering isn't as important, as neither overlaps. So having the most frequently used paths first is okay.
Alternatively you can utilize PHPs array parameters via ?p[]=$1&p[]=$2&p[]=3 query string here - if your script merely prefers them pre-split.
(Though it's more common to just use a catch-all rule, and let the script itself expand the segments out of the REQUEST_URI.)
See also: How do I transform my URL path segments into query string key-value pairs?
Optional segments prefix/opt?/.*
A common variation is to have optional prefixes within a rule. This usually makes sense if you have static strings or more constrained placeholders around:
RewriteRule ^(\w+)(?:/([^/]+))?/(\w+)$ ?main=$1&opt=$2&suffix=$3
Now the more complex pattern (?:/([^/])+)? there simply wraps a non-capturing (?:…) group, and makes it optional )?. The contained
placeholder ([^/]+) would be substitution pattern $2, but be empty if there's no middle /…/ path.
Capture the remainder /prefix/123-capture/…/*/…whatever…
As said before, you don't often want too generic rewrite patterns. It does however make sense to combine static and specific comparisons with a .* sometimes.
RewriteRule ^(specific)/prefix/(\d+)(/.*)?$ speci.php?id=$2&otherparams=$2
This optionalized any /…/…/… trailing path segments. Which then of course requires the handling script to split them up, and variabl-ify extracted parameters
itself (which is what Web-"MVC" frameworks do).
Trailing file "extensions" /old/path.HTML
URLs don't really have file extensions. Which is what this entire reference is about (= URLs are virtual locators, not necessarily a direct filesystem image).
However if you had a 1:1 file mapping before, you can craft simpler rules:
RewriteRule ^styles/([\w\.\-]+)\.css$ sass-cache.php?old_fn_base=$1
RewriteRule ^images/([\w\.\-]+)\.gif$ png-converter.php?load_from=$2
Other common uses are remapping obsolete .html paths to newer .php handlers, or just aliasing directory names only for individual (actual/real) files.
Ping-Pong (redirects and rewrites in unison) /ugly.html ←→ /pretty
So at some point you're rewriting your HTML pages to carry only pretty links, as outlined by deceze.
Meanwhile you'll still receive requests for the old paths, sometimes even from bookmarks. As workaround, you can ping-pong browsers to display/establish
the new URLs.
This common trick involves sending a 30x/Location redirect whenever an incoming URL follows the obsolete/ugly naming scheme.
Browsers will then rerequest the new/pretty URL, which afterwards is rewritten (just internally) to the original or new location.
# redirect browser for old/ugly incoming paths
RewriteRule ^old/teams\.html$ /teams [R=301,QSA,END]
# internally remap already-pretty incoming request
RewriteRule ^teams$ teams.php [QSA,END]
Note how this example just uses [END] instead of [L] to safely alternate. For older Apache 2.2 versions you can use other workarounds, besides also remapping
query string parameters for example:
Redirect ugly to pretty URL, remap back to the ugly path, without infinite loops
Spaces ␣ in patterns /this+that+
It's not that pretty in browser address bars, but you can use spaces in URLs. For rewrite patterns use backslash-escaped \␣ spaces.
Else just "-quote the whole pattern or substitution:
RewriteRule "^this [\w ]+/(.*)$" "index.php?id=$1" [L]
Clients serialize URLs with + or %20 for spaces. Yet in RewriteRules they're interpreted with literal characters for all relative path segments.
Frequent duplicates:
Catch-all for a central dispatcher / front-controller script
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^.*$ index.php [L]
Which is often used by PHP frameworks or WebCMS / portal scripts. The actual path splitting then is handled in PHP using $_SERVER["REQUEST_URI"]. So conceptionally it's pretty much the opposite of URL handling "per mod_rewrite". (Just use FallBackResource instead.)
Remove www. from hostname
Note that this doesn't copy a query string along, etc.
# ┌──────────┐
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] │
RewriteRule ^(.*)$ http://%1/$1 [R=301,L] │
# ↓ └───┼────────────┘
# └───────────────┘
See also:
· URL rewriting for different protocols in .htaccess
· Generic htaccess redirect www to non-www
· .htaccess - how to force "www." in a generic way?
Note that RewriteCond/RewriteRule combos can be more complex, with matches (%1 and $1) interacting in both directions even:
Apache manual - mod_rewrite intro, Copyright 2015 The Apache Software Foundation, AL-2.0
Redirect to HTTPS://
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
See also: https://wiki.apache.org/httpd/RewriteHTTPToHTTPS
"Removing" the PHP extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L] # or [END]
See also: Removing the .php extension with mod_rewrite
Aliasing old .html paths to .php scripts
See: http://httpd.apache.org/docs/2.4/rewrite/remapping.html#backward-compatibility
Rewrite from URL like "/page" to a script such as "/index.php/page"
See mod_rewrite, php and the .htaccess file
Redirect subdomain to a folder
See How can i get my htaccess to work (subdomains)?
Prevalent .htaccess pitfalls
Now take this with a grain of salt. Not every advise can be generalized to all contexts.
This is just a simple summary of well-known and a few unobvious stumbling blocks:
Enable mod_rewrite and .htaccess
To actually use RewriteRules in per-directory configuration files you must:
Check that your server has AllowOverride All enabled. Otherwise your per-directory .htaccess directives will go ignored, and RewriteRules won't work.
Obviously have mod_rewrite enabled in your httpd.conf modules section.
Prepend each list of rules with RewriteEngine On still. While mod_rewrite is implicitly active in <VirtualHost> and <Directory> sections,
the per-directory .htaccess files need it individually summoned.
The leading slash ^/ won't match
You shouldn't start your .htaccess RewriteRule patterns with ^/ normally:
RewriteRule ^/article/\d+$ …
↑
This is often seen in old tutorials. And it used to be correct for ancient Apache 1.x versions. Nowadays request paths are conveniently fully directory-relative in .htaccess RewriteRules. Just leave the leading / out.
· Note that the leading slash is still correct in <VirtualHost> sections though. Which is why you often see it ^/? optionalized for rule parity.
· Or when using a RewriteCond %{REQUEST_URI} you'd still match for a leading /.
· See also Webmaster.SE: When is the leading slash (/) needed in mod_rewrite patterns?
<IfModule *> wrappers begone!
You've probably seen this in many examples:
<IfModule mod_rewrite.c>
Rewrite…
</IfModule>
It does make sense in <VirtualHost> sections - if it was combined with another fallback option, such as ScriptAliasMatch. (But nobody ever does that).
And it's commonly distributed for default .htaccess rulesets with many open source projects. There it's just meant as fallback, and keeps "ugly" URLs work as default.
However you don't want that usually in your own .htaccess files.
Firstly, mod_rewrite does not randomly disengage. (If it did, you'd have bigger problems).
Were it really be disabled, your RewriteRules still wouldn't work anyway.
It's meant to prevent HTTP 500 errors. What it usually accomplishes is gracing your users with HTTP 404 errors instead. (Not so much more user-friendly if you think about it.)
Practically it just suppresses the more useful log entries, or server notification mails. You'd be none the wiser as to why your RewriteRules never work.
What seems enticing as generalized safeguard, often turns out to be an obstacle in practice.
Don't use RewriteBase unless needed
Many copy+paste examples contain a RewriteBase / directive. Which happens to be the implicit default anyway. So you don't actually need this. It's a workaround for fancy VirtualHost rewriting schemes, and misguessed DOCUMENT_ROOT paths for some shared hosters.
It makes sense to use with individual web applications in deeper subdirectories. It can shorten RewriteRule patterns in such cases. Generally it's best to prefer relative path specifiers in per-directory rule sets.
See also How does RewriteBase work in .htaccess
Disable MultiViews when virtual paths overlap
URL rewriting is primarily used for supporting virtual incoming paths. Commonly you just have one dispatcher script (index.php) or a few individual handlers (articles.php, blog.php, wiki.php, …). The latter might clash with similar virtual RewriteRule paths.
A request for /article/123 for example could map to article.php with a /123 PATH_INFO implicitly. You'd either have to guard your rules then with the commonplace RewriteCond !-f+!-d, and/or disable PATH_INFO support, or perhaps just disable Options -MultiViews.
Which is not to say you always have to. Content-Negotiation is just an automatism to virtual resources.
Ordering is important
See Everything you ever wanted to know about mod_rewrite
if you haven't already. Combining multiple RewriteRules often leads to interaction. This isn't something to prevent habitually per [L] flag, but a scheme you'll embrace once versed.
You can re-re-rewrite virtual paths from one rule to another, until it reaches an actual target handler.
Still you'd often want to have the most specific rules (fixed string /forum/… patterns, or more restrictive placeholders [^/.]+) in the early rules.
Generic slurp-all rules (.*) are better left to the later ones. (An exception is a RewriteCond -f/-d guard as primary block.)
Stylesheets and images stop working
When you introduce virtual directory structures /blog/article/123 this impacts relative resource references in HTML (such as <img src=mouse.png>).
Which can be solved by:
Only using server-absolute references href="/old.html" or src="/logo.png"
Often simply by adding <base href="/index"> into your HTML <head> section.
This implicitly rebinds relative references to what they were before.
You could alternatively craft further RewriteRules to rebind .css or .png paths to their original locations.
But that's both unneeded, or incurs extra redirects and hampers caching.
See also: CSS, JS and images do not display with pretty url
RewriteConds just mask one RewriteRule
A common misinterpetation is that a RewriteCond blocks multiple RewriteRules (because they're visually arranged together):
RewriteCond %{SERVER_NAME} localhost
RewriteRule ^secret admin/tools.php
RewriteRule ^hidden sqladmin.cgi
Which it doesn't per default. You can chain them using the [S=2] flag. Else you'll have to repeat them. While sometimes you can craft an "inverted" primary rule to [END] the rewrite processing early.
QUERY_STRING exempt from RewriteRules
You can't match RewriteRule index.php\?x=y, because mod_rewrite compares just against relative paths per default. You can match them separately however via:
RewriteCond %{QUERY_STRING} \b(?:param)=([^&]+)(?:&|$)
RewriteRule ^add/(.+)$ add/%1/$1 # ←──﹪₁──┘
See also How can I match query string variables with mod_rewrite?
.htaccess vs. <VirtualHost>
If you're using RewriteRules in a per-directory config file, then worrying about regex performance is pointless. Apache retains
compiled PCRE patterns longer than a PHP process with a common routing framework. For high-traffic sites you should however consider
moving rulesets into the vhost server configuration, once they've been battle-tested.
In this case, prefer the optionalized ^/? directory separator prefix. This allows to move RewriteRules freely between PerDir and server
config files.
Whenever something doesn't work
Fret not.
Compare access.log and error.log
Often you can figure out how a RewriteRule misbehaves just from looking at your error.log and access.log.
Correlate access times to see which request path originally came in, and which path/file Apache couldn't resolve to (error 404/500).
This doesn't tell you which RewriteRule is the culprit. But inaccessible final paths like /docroot/21-.itle?index.php may give away where to inspect further.
Otherwise disable rules until you get some predictable paths.
Enable the RewriteLog
See Apache RewriteLog docs. For debugging you can enable it in the vhost sections:
# Apache 2.2
RewriteLogLevel 5
RewriteLog /tmp/rewrite.log
# Apache 2.4
LogLevel alert rewrite:trace5
#ErrorLog /tmp/rewrite.log
That yields a detailed summary of how incoming request paths get modified by each rule:
[..] applying pattern '^test_.*$' to uri 'index.php'
[..] strip per-dir prefix: /srv/www/vhosts/hc-profi/index.php -> index.php
[..] applying pattern '^index\.php$' to uri 'index.php'
Which helps to narrow down overly generic rules and regex mishaps.
See also:
· .htaccess not working (mod_rewrite)
· Tips for debugging .htaccess rewrite rules
Before asking your own question
As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
by including prior research and attempts (avoid redundant answers), demonstrate basic regex understanding, and:
Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
The complete RewriteRule set, but also single out the presumed defective one.
Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.
This nets quicker and more exact answers, and makes them more useful to others.
Comment your .htaccess
If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
all the more interested in not treating them like magic blackboxes.
It's not "SEO"-URLs
Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.
None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.
What "pretty" URLs should conceptionally be used for is making websites user-friendly.
Having readable and obvious resource schemes.
Ensuring URLs are long-lived (AKA permalinks).
Providing discoverability through /common/tree/nesting.
However don't sacrifice unique requirements for conformism.
Tools
There are various online tools to generate RewriteRules for most GET-parameterish URLs:
http://www.generateit.net/mod-rewrite/index.php
http://www.ipdistance.com/mod_rewrite.php
http://webtools.live2support.com/misc_rewrite.php
Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.
Alternatives to mod_rewrite
Many basic virtual URL schemes can be achieved without using RewriteRules. Apache allows PHP scripts to be invoked without .php extension, and with a virtual PATH_INFO argument.
Use the PATH_INFO, Luke
Nowadays AcceptPathInfo On is often enabled by default. Which basically allows .php and other resource URLs to carry a virtual argument:
http://example.com/script.php/virtual/path
Now this /virtual/path shows up in PHP as $_SERVER["PATH_INFO"] where you can handle any extra arguments however you like.
This isn't as convenient as having Apache separate input path segments into $1, $2, $3 and passing them as distinct $_GET variables to PHP. It's merely emulating "pretty URLs" with less configuration effort.
Enable MultiViews to hide the .php extension
The simplest option to also eschew .php "file extensions" in URLs is enabling:
Options +MultiViews
This has Apache select article.php for HTTP requests on /article due to the matching basename. And this works well together with the aforementioned PATH_INFO feature. So you can just use URLs like http://example.com/article/virtual/title. Which makes sense if you have a traditional web application with multiple PHP invocation points/scripts.
Note that MultiViews has a different/broader purpose though. It incurs a very minor performance penalty, because Apache always looks for other files with matching basenames. It's actually meant for Content-Negotiation, so browsers receive the best alternative among available resources (such as article.en.php, article.fr.php, article.jp.mp4).
SetType or SetHandler for extensionless .php scripts
A more directed approach to avoid carrying around .php suffixes in URLs is configuring the PHP handler for other file schemes. The simplest option is overriding the default MIME/handler type via .htaccess:
DefaultType application/x-httpd-php
This way you could just rename your article.php script to just article (without extension), but still have it processed as PHP script.
Now this can have some security and performance implications, because all extensionless files would be piped through PHP now. Therefore you can alternatively set this behaviour for individual files only:
<Files article>
SetHandler application/x-httpd-php
# or SetType
</Files>
This is somewhat dependent on your server setup and the used PHP SAPI. Common alternatives include ForceType application/x-httpd-php or AddHandler php5-script.
Again take note that such settings propagate from one .htaccess to subfolders. You always should disable script execution (SetHandler None and Options -Exec or php_flag engine off etc.) for static resources, and upload/ directories etc.
Other Apache rewriting schemes
Among its many options, Apache provides mod_alias features - which sometimes work just as well as mod_rewrites RewriteRules. Note that most of those must be set up in a <VirtualHost> section however, not in per-directory .htaccess config files.
ScriptAliasMatch is primarily for CGI scripts, but also ought to works for PHP. It allows regexps just like any RewriteRule. In fact it's perhaps the most robust option to configurate a catch-all front controller.
And a plain Alias helps with a few simple rewriting schemes as well.
Even a plain ErrorDocument directive could be used to let a PHP script handle virtual paths. Note that this is a kludgy workaround however, prohibits anything but GET requests, and floods the error.log by definition.
See http://httpd.apache.org/docs/2.2/urlmapping.html for further tips.
A frequent question about URL rewriting goes something like this:
I currently have URLs that look like this:
http://example.com/my-blog/entry.php?id=42
http://example.com/my-blog/entry.php?id=123
I made them pretty like this:
http://example.com/my-blog/42--i-found-the-answer
http://example.com/my-blog/123--count-on-me
By using this in my .htaccess file:
RewriteRule my-blog/(\d+)--i-found-the-answer my-blog/entry.php?id=$1
But I want them to look like this:
http://example.com/my-blog/i-found-the-answer
http://example.com/my-blog/count-on-me
How can I change my .htaccess file to make that work?
The simple answer is that you can't.
Rewrite rules don't make ugly URLs pretty, they make pretty URLs ugly
Whenever you type in a URL in a web browser, or follow a link, or display a page that references an image, etc, the browser makes a request for a particular URL. That request ends up at a web server, and the web server gives a response.
A rewrite rule is simply a rule that says "when the browser requests a URL that looks like X, give them the same response as if they'd requested Y".
When we make rules to handle "pretty URLs", the request is the pretty URL, and the response is based on the internal ugly URL. It can't go the other way around, because we're writing the rule on the server, and all the server sees is the request the browser sent it.
You can't use information that you don't have
Given this basic model of what a rewrite rule does, imagine you were giving the instructions to a human. You could say:
If you see a number in the request, like the "42" in "http://example.com/my-blog/42--i-found-the-answer", put that number on the end of "my-blog/entry.php?id="
But if the information isn't there in the request, your instructions won't make any sense:
If the request has "my-blog" in it, like "http://example.com/my-blog/i-found-the-answer", put the right number on the end of "my-blog/entry.php?id="
The person reading those instructions is going to say "Sorry, how do I know what the right number is?"
Redirects: "This URL is currently out of office..."
Sometimes, you see rules that are the other way around, like this:
RewriteRule my-blog/entry.php?id=(\d+) my-blog/$1--i-found-the-answer [R]
This rule does match an ugly URL on the left, and produce a pretty URL on the right. So surely we could write it without the ID at the beginning of the pretty part?
RewriteRule my-blog/entry.php?id=(\d+) my-blog/i-found-the-answer [R]
The important difference is the [R] flag, which means that this rule is actually a redirect - instead of "serve the response from this URL", it means "tell the browser to load this URL instead".
You can think of this like one of those automated e-mail replies, saying "Sorry, Joe Bloggs is currently on holiday; please send your message to Jane Smith instead." In the same way, the redirect above tells the browser "Sorry, there's no content for http://example.com/my-blog/entry.php?id=42; please request http://example.com/my-blog/42--i-found-the-answer instead.
The important point of this analogy is that the above message wouldn't be much use if there wasn't actually anyone called Jane Smith working there, or if they had no idea how to answer the questions Joe Bloggs normally dealt with. Similarly, a redirect is no use if the URL you tell the browser to request doesn't actually do anything useful. Once the browser follows the redirect, it's going to make a new request, and when the server receives the new request, it still won't know what the ID number is.
But some sites do it, so it must be possible!
A web server only has the information present in the request, but how it uses that information is up to you.
For instance, rather than looking up a blog post by ID, you could store its URL directly in the database, then write some code to do the matching directly in PHP, Python, node.js, etc. Or you could have the same URL show different content based on the language the user has set in their browser, or based on a cookie, etc.
Another thing you can do is use a form (or API request) with a method of POST rather than GET. That means additional information is sent in the "body" of the request, separate from the URL. It still has to be sent, but it's not as obvious in the browser, won't be included in bookmarks, etc.
But you can't write a single line in a .htaccess file that performs miracles.
I am not using Virtual Hosts or anything fancy though I have some .htaccess files setup. Following is my rewrite rule in httpd.conf:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/app/smsapi [NC]
RewriteRule (.*) https://www.example.com/uri=%{REQUEST_URI} [R,L]
This rule basically says that if the uri does not begin with /app/smsapi then fire the rewrite. But when I restart the server and try it I get some weird results.
When I request the URL https://www.example.com/app/smsapi/index.php, I get a 200 Success code which is as expected. But, when I request the URL http://www.example.com/app/smsapi/index.php, it redirects to https://www.example.com/uri=/app/smsapi/index.php. So it actually fires the rule even though the request URI does not satisfy the condition.
So, then I decided to turn off the rewrite rules and give it a go. Now, both those URL give me a 200 Success code.
Now, I know this problem cannot be solved easily by other people who do not have access to the server, but am I right in saying that this is certainly a problem with REQUEST_URI not firing correctly? I have shown that without the rewrite rule, everything works normally, but with the rewrite rule, the second URL is redirected. Therefore, the redirection must be caused by the rewrite rule? Additionally, the condition for redirect rule is not satisfied. Doesn't this prove that there is something wrong with the functioning of the rewrite rule?
Is there any other possibility?
UPDATE
Something very weird is happening here. I setup a local server and tried the same rule and what I got for the URL http://192.168.0.112/app/ is
http://192.168.0.112/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/uri=/app/
which is correct because as long as the URL is not like /app/smsapi, it should redirect it. Wonder why this is not happening on the real server. Also, where you insert these rules seems to make a difference. (I am only including these rules after the LoadModule command).
On localhost, if I put these rules either above or below the Directory section, it won't work. But, if I include it inside the Directory section it will.
On server, if I include the rules inside the Directory section, they won't work. But, if I include them either above or below the Directory section, they start working.
This seems to me to be due to a difference in the versions. My localhost is an Ubuntu Desktop 16.04 running Apache 2.4.18. While the server is CentOS 6.8 running Apache 2.2.15.
But, i think the mystery as to why on the server redirect happens only once (though it is configured to go upto 20 times) has something to do with https. Which is also related to the original problem in which https is redirected even on a non-matching rule.
Clues anyone?
UPDATE
I updated the httpd.conf file with the same rules but I used http:// instead of https:// and it gave me the correct result with 20 redirects. That means I have isolated the problem to https.
You are reporting the exact issue in the first phrase: "I am not using Virtual Hosts or anything fancy though I have some .htaccess files setup"
.htaccess is "fancy" and overcomplicated, not virtualhosts.
If you had defined that RewriteCond in virtualhost in the first place it would work, but .htaccess is per-dir context (aka a nightmare) and the regex ^/ will never match in that context.
If you want to match REQUEST_URI in per-dir context (directory or .htaccess) you need to drop the initial slash, that is:
RewriteCond %{REQUEST_URI} !^app/smsapi [NC]
Extra, also consider you MAY NOT need to add a RewriteCond for this:
RewriteRule ^(?!app/smsapi)(.*) https://www.example.com/uri=$1 [R,L]
I'm having some trouble with Apache's mod_rewrite. One of the things I'm trying to get it to do is hide some of my implementation details, so that, for example, the user sees the URL http://www.mysite.com/login but Apache responds with the page at http://www.mysite.com/doc_root/login.php instead (preferably without showing the user that it's a PHP file or the directory structure). Here's what I have in my .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?mysite.com*
RewriteRule ^/(\w+) /doc_root/$1.php [L]
#Redirect http://www.mysite.com to the login page
RewriteRule ^/?$ https://www.mysite.com/doc_root/login.php
But when I go to http://www.mysite.com/login, I get a 404 error even though the page exists. I clearly don't have a great understanding of how the mod_rewrite conditionals and rules work, so can anyone please tell me what I'm doing wrong? Thanks.
Take doc_root out of all the stuff you have it in. That will give you the result you're asking for. However I'm not sure if it's desired or not. How are you going to force someone to login if they manually type http://www.mysite.com/index.php?
Also if you're trying to force all traffic to SSL it's better to use a second VirtualHost and Redirect instead of mod_rewrite. Those are all questions probably better suited for ServerFault
Unless your site has a bunch of different domain names, and you only want mysite.com to do the rewriting, you don't need the RewriteCond. (Potential problem. Apache likes to dick around with the domain name unless you set UseCanonicalName off. If the name isn't what it's expecting, the rewrite won't happen.)
In RewriteCond (and RewriteRule) patterns, . matches any character. Add a backslash before them. (Minor bug. Shouldn't cause rewrites to fail, but they would match stuff like "mysite-com" as well.)
mod_rewrite is actually a URL-to-filename filter. Though it is often used to rewrite URLs to other URLs, sometimes it will misbehave if what you're rewriting to is a URL and it can't tell. (Especially if what it's rewriting to would be an alias, or would otherwise not translate directly to a real filename.) If you add a [PT] flag onto your rule, though, it will consider the rewritten thing a URL and pass it along to the other filters (including the ones that turn URLs into filenames).
Do you really need "/doc_root"? The document root should already be set up in Apache using the DocumentRoot directive, and shouldn't need to be part of the URL unless you have multiple apps on the same domain (in which case it's the app root; the document root doesn't change).
UPDATE:
Another thing i just thought about: Rewrite rules work differently in .htaccess files. Apache likes to strip off the leading slash. So you will probably want to get rid of the first slash in your patterns, or at least make it optional (^/?login instead of ^/login).
^/?(\w+) will match /doc_root/login.php, and cause a rewrite to /doc_root/doc_root.php. You should probably have a $ at the end of your pattern.