Reputation: 451
I would like to be able to process the following segments of a URL to an application:
https://example.com/app/date/category
Where
/app
is the directory on the website/date
is a string value to be passed eg; January_7
/category
is a text value to be passed eg; births
and route it to index.php
for processing.
Can this be accomplished using the .htaccess
file?
Upvotes: 1
Views: 762
Reputation: 45829
Yes, you can do this in .htaccess
. How you want the values passed to your PHP script can determine exactly how you'd write the necessary directives in .htaccess
.
This assumes your .htaccess
file is located in the /app
subdirectory and index.php
is also located at /app/index.php
.
One way is to use FallbackResource
that specifies the URL that all requests that should be rewritten to that would otherwise trigger a 404. For example:
FallbackResource /app/index.php
Then, in index.php
you would parse the required path segments from the PHP superglobal: $_SERVER['REQUEST_URI']
. Note that all URLs are routed to index.php
, including those that don't match your pattern, so it is up to your PHP to process this accordingly.
Alternatively, if you want to pass the individual path segments to index.php
in the form of GET params then you could do something like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\w+)/([\w-]+)$ index.php?date=$1&category=$1 [QSA,L]
The first two conditions (RewriteCond
directives) ensure the request is not for a file or directory (to avoid rewriting static resources).
(\w+)
captures the "date" path segment, which is later referenced in the substitution with the $1
backreference. \w
is a shorthand character class representing the characters 0-9
, a-z
, A-Z
and _
.
([\w-]+)
captures the "category" path segment, which is later referenced in the substitution with the $2
backreference. This also allows -
(hyphen) in addition to the characters mentioned above.
Then, in your PHP code you access $_GET['date']
and $_GET['category']
to access your values.
In this second example, the request is only rewritten when it matches the expected URL request pattern, ie. /app/<date>/<category>
.
Upvotes: 1