问题
I am stick in a situation of a websites URL. Here I am describing it using an e-commerce site.
Product Categories
Women ------> womens-clothing (sub-category)
---------> womens-top (child)
---------> womens-dress (child)
public_html
is the root directory. I want to create URLs like this -->
Case 1 -> If user wants to view all the products under a sub-category (say Womens-clothing
). Then I want the URL to be www.website.com/womens-clothing/(may be some parameters here)
.
Case 2 -> If user wants to view all the products under a specific child (say womens-top
which is under womens-clothing
sub-category) then I want the URL to be www.website.com/womens-clothing/womens-tops/(may be some parameters here)
.
So my question is do I need to create a directory for each sub-categories
and child-categories
under its parent categories or it can be done with HTACCESS
in any single page without creating directories ..??
回答1:
Doing this by creating directories (while works) is almost idiotic as it would be massively time consuming and hard to manage.
Yes! .htaccess
(where apache is concerned) is the right choice for a solution to your problem.
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ index.php?page=$1 [NC,L]
This snippet is a great example of how a .htaccess
file can be used for this purpose.
Then, in your index.php
file, you can get the url by $_GET['page]
So, say your at the page; www.website.com/womens-clothing/womens-tops/
The $_GET['page]
would return womens-clothing/womens-tops/
.
Then, just $url = explode('/', $_GET['page]);
$url[0]
= womens-clothing
$url[1]
= womens-tops
Doing this will give you your parameters.
Also, use an if (isset($url[NUM])) {}
so you don't get errors for an out of range index.
Thats the basis of it anyway.
Explanation
all this is really doing is hiding index.php
from the url, as well as serving every 'directory' in the url as a get request.
This is known as URL Rewriting
, and involves apaches mod_rewrite
function.
回答2:
No, Not at all! Creating a directory per URL neither is dynamic, nor applicable when your site grows. Soon your website maintenance gets overwhelming.
Solution to your problem is to keep with URL Rewrite(mod_rewrite for Apache web server) along with .htaccess & creating a kinda URL Aliases.
Consult these questions here:
Generate URL Alias?? in PHP
How do I create a people-friendly URL using an alias and ID from database?
来源:https://stackoverflow.com/questions/40956502/dynamic-url-based-htaccess