I am currently trying to set up a rewrite rule to set up an internal redirect for a more SEO-friendly url-structure.
I want to show:
/find-teacher/primary-school.php
instead of the sad looking:
/find-teacher/subject-class-choose.php?school=primary-school
After I read some posts and tutorials about the rewrite rule and rewrite cond, I came up with this:
In my choose-school.php I have as a link with the nice looking url:
<a href="https://www.example.com/find-teacher/primary-school.php"> Primary School</a>
In my .htaccess:
RewriteCond %{REQUEST_URI} ^find-teacher/primary-school.php$ RewriteRule ^find-teacher/([a-z-]+)-([0-9]+).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
Now if I got that right, the RewriteCond
part checks if the following url is requested. If that is the case, then the part of ([a-z-]+)-([0-9]+)
is replaced by the $1
of the substitution part (/find-teacher/subject-class-choose.php?school=$1
)
Problem is that I am redirected to my error page if I click on /find-teacher/primary-school.php
Advertisement
Answer
You don’t need both a RewriteCond and a RewriteRule here, because they are (or should be) both checking the same thing.
However, currently, there is no URL which will match both patterns. Let’s break down the problem.
To check specifically for the URL /find-teacher/primary-school.php
, you could just write:
RewriteRule ^find-teacher/primary-school.php$ /find-teacher/subject-class-choose.php?school=primary-school [NC]
The next step is to “capture” the “primary-school” with (
and )
, and place it dynamically onto the target with $1
:
RewriteRule ^find-teacher/(primary-school).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
Finally, we can make the pattern match any letters or hyphens instead of an exact string, using the regex [a-z-]+
:
RewriteRule ^find-teacher/([a-z-]+).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
In the rule in your question, you’ve added an extra part to the regex: -([0-9]+)
. This matches -
and then a number. To capture that number, you’d put $2
somewhere in your target:
RewriteRule ^find-teacher/([a-z-]+)-([0-9]+).php$ /find-teacher/subject-class-choose.php?school=$1&id=$2 [NC]
This would match something like /find-teacher/primary-school-123.php
, and turn it into /find-teacher/subject-class-choose.php?school=primary-school&id=123
.
Two final notes:
- depending how your Apache configuration is set up, you may or may not need to include the leading
/
in your patterns, i.e. start them with^/
- I find a nice way to debug rewrite rules is to make them redirect your browser, by adding
R=temp
to the flags (e.g.[NC,R=temp]
); that way, you don’t have to rely on your PHP code to tell you what URL was requested