Setup clean URLs like CodeIgniter

2019-09-03 23:55发布

I like the way CodeIgniter cleans URLs for sites, however, I have a site that is too involved to start over using the CI framework (at least for now), and I don't need the depth CI provides, I only have one level deep.

Is there an easy way to do this easily using straight PHP?

index.php?id=2454
index.php/2454/

NOTE: I need a straight PHP solution because the server is Windows and .htaccess is not setup to work.

4条回答
仙女界的扛把子
2楼-- · 2019-09-03 23:56

If you use mod_rewrite in apache you can allow your application to dispatch requests as you want.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Say your server is located @ http://coolguy.com and a users accesses http://coolguy.com/mycleanurl/

With the above rewrite rule in your .htaccess or apache configuration you can intercept which url is being accessed via $_SERVER['REDIRECT_URL'] and send it off to the specific code point you want.

The "RewriteCond" directives i have in there are used to ignore this rewrite rule if there exists a file directly at the location the user has specified, this is handy for static assets like CSS and images where you dont want to have to dispatch these requests yourself.

查看更多
该账号已被封号
3楼-- · 2019-09-04 00:14

Check out $_SERVER['PATH_INFO'] - it returns anything trailing the script filename but preceding the query.

For example, in the URL:

http://www.domain.com/index.php/var1/var2

$_SERVER['PATH_INFO'] would contain /var1/var2

You could then write a function in your __construct() or init(), etc, to parse the path (e.g. explode("/", $_SERVER['PATH_INFO'])) and use the resulting array as variables.

查看更多
【Aperson】
4楼-- · 2019-09-04 00:18

Are you using Apache? If so, look into files called .htaccess. They rewrite the URL when they're stored in your directory. So if you put an .htaccess file in your web root with

# .htaccess
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/www/
RewriteRule ^(.*)$ /www/$1 [L]

then when a person goes to the URL yourdomain.com/page1, it will actually retrieve the resource yourdomain.com/www/page1 on your server, but their browser won't see the www.

So, for very simple URL rewriting you can use this to hide the ?var=val&var2=val2 crap in the URL

Information on the rules is here

查看更多
家丑人穷心不美
5楼-- · 2019-09-04 00:18

If your using PHP on windows and want to do URL Rewriting you have two choices:

  • Url Rewrite (which allows you to use rewrite rules in the web.config) http://www.iis.net/download/urlrewrite - Open the site in IIS Manager and select "Url Rewriting", then add your rules.

  • Buy Helicon-APE or similar (which allows you to use a native .htaccess file) http://www.helicontech.com/ape/ - we use this on our shared windows hosting servers with great success

查看更多
登录 后发表回答