需要mod_rewrite指南

时间:2016-04-20 22:58:29

标签: php apache .htaccess mod-rewrite

我在localhost xampp上有一个虚拟名称为mysite.com的网站

我正在尝试使用以下代码使URL更简单但不起作用。

RewriteEngine On

RewriteRule    ^$       index.php
RewriteRule    ^home$   index.php

上面的代码有效但硬编码。因此,如果我用^.*$替换主页,那么网站资产就会丢失。 CSS等不起作用。

我想要的是一条规则,只是简单地告诉我域后的所有内容,以便我可以在后端使用这些并显示特定的页面。

mysite.com -gets- 
mysite.com/ -gets- /
mysite.com/home -gets- home
mysite.com/products/abc -gets- products/abc
mysite.com/products/used/xyz -gets- products/used/xyz

请指导

2 个答案:

答案 0 :(得分:1)

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* /index.php

上面的代码给出了index.php文件的URL中的所有内容。

如果你想将它用于每个网址,除了不以" png"," jpg"," css"," js& #34;" GIF"你可以使用:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.css$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*\.js$ [NC]
RewriteRule .* /index.php

答案 1 :(得分:0)

要获得特定的uri,你实际上需要使用php来获取它而不是只有一个mod_rewrite - 注意:你必须设置mod重写才能获得正确的格式。

如果你想在数组中使用uri,可以使用mixed parse_url ( string $url [, int $component = -1 ] )

来自PHP手册http://php.net/manual/en/function.parse-url.php

  

此函数解析URL并返回一个关联数组,其中包含存在的URL的各种组件。

     

此功能并不是为了验证给定的URL,而是将其分解为上面列出的部分。部分URL也被接受,parse_url()会尽力正确解析它们。

或者如果你想要整个东西使用php服务器变量$_SERVER['REQUEST_URI']