Home >Backend Development >PHP Tutorial >How Can I Create More User-Friendly URLs in PHP?
Creating Friendly URLs in PHP
Oftentimes, URLs are generated in a way that displays information directly in the query string, such as:
www.domain.com/profile.php?u=12345
However, modern web design principles advocate for more user-friendly and readable URLs, like:
www.domain.com/profile/12345
To achieve this in PHP, consider utilizing one of the following methods:
Method 1: Using mod_rewrite in .htaccess
With mod_rewrite enabled in your .htaccess file, you can use a rule such as:
RewriteEngine on RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=
This rule maps requests from:
/news.php?news_id=63
to:
/news/63.html
Method 2: Forcing PHP Execution with ForceType
Another option is to use ForceType to redirect all requests to a specific path to be processed by PHP. In your .htaccess file, add the following:
<Files news> ForceType application/x-httpd-php </Files>
This forces any request that includes "/news" in the path to be executed by PHP. Your index.php file can then process the request based on the $_SERVER['PATH_INFO'] variable:
<?php echo $_SERVER['PATH_INFO']; // Outputs '/63.html' ?>
The above is the detailed content of How Can I Create More User-Friendly URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!