如何使用 .htaccess 创建友好的 URL? [英] How can I create friendly URLs with .htaccess?

查看:34
本文介绍了如何使用 .htaccess 创建友好的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 .htaccess 时遇到了困难.我想为我正在处理的网站创建友好的 URL...

I'm having a hard time with .htaccess. I want to create friendly URLs for a site I'm working on...

基本上我想转换这个:

http://website.com/index.php?ctrl=pelicula&id=0221889
http://website.com/index.php?ctrl=pelicula&id=0160399&tab=posters

进入这个:

http://website.com/pelicula/0221889/
http://website.com/pelicula/0221889/posters/

如果我以后需要它,我还想知道如何像这样将文章标题添加到 URL 的末尾(我使用的是 PHP):

In case I need it later I would also want to know how to add the article title to the end of the URL like this (I'm using PHP):

http://website.com/pelicula/0221889/the-article-name/
http://website.com/pelicula/0221889/the-article-name/posters/

注意:Stackoverflow 方法对我来说也很好,比如这个问题的 url 是:

Note: Stackoverflow method is also good for me, for example the url of this question is:

http://stackoverflow.com/questions/3033407/htacces-to-create-friendly-urls-help-needed

但是你可以在 id 后面放任何东西,它也可以工作.像这样:

But you can put anything after the id and it will also work. like this:

http://stackoverflow.com/questions/3033407/just-anything-i-want

我使用了一些自动网络工具来创建 .htacces 文件,但它无法正常工作.所以我请求你的帮助.

I have used some automatic web tools for creating the .htacces file, but its not working correctly. So I ask for your help.

如果您能推荐 .htacces 最佳实践和建议,我也会很高兴..

I will also be glad if you can recommend .htacces best practices and recommendations..

根据我得到的一些答案,我把这个:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/([^/]+)/([^/]+)/?([^/]*)/?$ index.php?ctrl=$1&id=$2&tab=$3 [QSA,L]
</IfModule>

但我收到默认主机找不到页面"错误.

But I get the default host 'page not found' error.

我也试过:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/(d+)/([^/]+)/?$ index.php?ctrl=$1&id=$2&tab=$3 [QSA,L]
    RewriteRule ^([^/]+)/(d+)/?$         index.php?ctrl=$1&id=$2 [QSA,L]
    RewriteRule ^([^/]+)/?$               index.php?ctrl=$1 [QSA,L]
</IfModule>

这也不起作用.它带我进入我的默认 404.php 页面.

This also does not work. It takes me to my default 404.php page.

mod_rewrite 已启用并正常工作.

mod_rewrite is enabled and working.

帮助!

推荐答案

http://website.com/ 的文档根目录中,我会放一个 htaccess像这样的文件:

In the document root for http://website.com/ I'd put an htaccess file like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

然后在您的 PHP 脚本中,您可以随意操作 $_GET['url'] 变量:

Then in your PHP script you can manipulate the $_GET['url'] variable as you please:

$path_components = explode('/', $_GET['url']);
$ctrl=$path_components[0];
$id=$path_components[1];
$tab=$path_components[2];

这篇关于如何使用 .htaccess 创建友好的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆