关于 url 重写
我在一个平台工作,最近遇到了如何重写链接的问题。 首先我想给你一个例子:
假设这是原始链接:
category.php?_uri=category/subcategory/subcategory2...
重写结构是:
domain_path/category/subcategory/subcategory2...
从我看到的大多数主要平台的链接都是这样写的,我的问题是如何制作类似的东西?
在我尝试逻辑思考后,我们得到了类似的东西:
.htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ category.php?_uri=$1 [L,QSA]
我想使用:
$_SERVER["REQUEST_URI"]
但我不明白如何检查是一个类别还是一篇文章(因为对于文章我想使用相同的结构,例如:domain_path/ Article_name) ...调用内容的最佳方式是什么?
I work at a platform and recently encountered a problem with how to rewrite links.
First I want to give you an exemple:
Let's say that is the original link:
category.php?_uri=category/subcategory/subcategory2...
The rewrite structure is:
domain_path/category/subcategory/subcategory2...
From what I saw most major platforms links are written so, and my question is how can make something similar?
After I tried to think logically we came to something like:
.htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ category.php?_uri=$1 [L,QSA]
And I wanted to work with:
$_SERVER["REQUEST_URI"]
But I do not understand how to check if is a category or an article (because for article I want to use same structure ex: domain_path/article_name) ... and which is the best way to call the content?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议你这样做
当访问像
/foo/bar/baz
这样的 URL 时,你会I'd suggest you do
When accessing an URL like
/foo/bar/baz
, you'll have通常,您会像上面所做的那样,在
.htaccess
文件中使用RewriteRule
捕获 URL,然后使用 PHP 解析它。使用上面的代码,它会位于$_SERVER['REQUEST_URI']
变量中,然后您可以开始对其进行操作:上面的代码将为您提供一个 URL 段数组,每个段都进行分割正斜杠。如何解析 URL 由您决定。
通过区分目录页面和文章、CMS 页面(我认为这是您遇到的问题),您可以通过多种方式解决它。就我个人而言,我通过使用第一个 URL 段来区分内容。因此它可能是
/articles
或/products
等等。Usually you'd catch the URL with a
RewriteRule
in an.htaccess
file, as you have done above, and then parse it with PHP. Using the above, it'd be in the$_SERVER['REQUEST_URI']
variable and then you can start acting on it:The above would then give you an array of your URL segments, split at each forward slash. How you parse your URL is up to you.
With differentiating between catalogue pages and say, articles, or a CMS page (which I think is the problem you're having) you can go about it in many ways. Personally, I differentiate between content by using the first URL segment. So it may be
/articles
, or/products
, and so on.如果您依赖于使用
category.php
和article.php
,您可以执行类似这样的操作。最好的方法是通过像这样的单个前端
控制器然后需要在配置中定义路径并根据它们检查请求的 URL(来自
$_SERVER['REQUEST_URI']
)。您可以看看
Zend_Router
工作并遵循类似的模式If you're tied to using
category.php
andarticle.php
, you could do something like thisThe nicest way to do this is through a single front controller like this
You will then need to define paths in your config and check the requested URL (from
$_SERVER['REQUEST_URI']
) against them.You could have a look at how
Zend_Router
works and follow a similar pattern