You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用简单PHP函数实现Clean URL?单入口站点URL优化求助

How to Implement Clean URLs for Your Single-Entry PHP Site

Hey there! Let's walk through setting up Clean URLs for your single-entry PHP project. Just a heads up: this requires both server configuration and a bit of PHP logic in your index.php—I'll cover both, with the PHP function you asked for front and center.


First: Server Configuration (Apache & Nginx Examples)

Clean URLs rely on your web server redirecting all incoming requests to your index.php file. Here's how to set that up:

For Apache Users

Create a .htaccess file in your site's root directory with this code:

RewriteEngine On
# Skip redirects if the request is for a real file/directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Forward all other requests to index.php, passing the original URL as a parameter
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

For Nginx Users

Add this block to your server configuration (usually in nginx.conf or your site-specific config file):

location / {
    try_files $uri $uri/ /index.php?url=$request_uri;
}

Second: The PHP Function for index.php

Drop this function at the very top of your index.php (before any HTML output or other code). It'll parse the clean URL and map it to your site's content:

<?php
// Parse clean URLs into usable route data
function parseCleanUrl() {
    // Grab the URL path passed from the server config
    $url = isset($_GET['url']) ? rtrim($_GET['url'], '/') : '';
    // Sanitize the URL to prevent malicious input
    $url = filter_var($url, FILTER_SANITIZE_URL);
    // Split the URL into parts (e.g., "blog/post-123" becomes ["blog", "post-123"])
    $urlParts = explode('/', $url);

    // Default route if no URL is specified (your homepage)
    $controller = !empty($urlParts[0]) ? $urlParts[0] : 'home';
    $action = !empty($urlParts[1]) ? $urlParts[1] : 'index';
    // Any extra segments become parameters (e.g., "user/profile/123" has params ["123"])
    $params = array_slice($urlParts, 2);

    // Return the parsed route data for use elsewhere
    return [
        'controller' => $controller,
        'action' => $action,
        'params' => $params
    ];
}

// Run the function to get your route
$route = parseCleanUrl();

// Example: Use the route to load the right content
// If someone visits yoursite.com/blog/my-first-post, $route will point to the blog section
switch($route['controller']) {
    case 'home':
        include 'pages/home.php'; // Load your homepage
        break;
    case 'blog':
        include 'pages/blog-post.php'; // Load the blog post page
        $postSlug = $route['action']; // Use the second URL segment as the post slug
        break;
    case 'about':
        include 'pages/about.php'; // Load your about page
        break;
    default:
        include 'pages/404.php'; // Load a 404 page for invalid routes
        break;
}
?>

Quick Tips to Avoid Headaches

  • Make sure your server has URL rewriting enabled: For Apache, that's mod_rewrite; for Nginx, rewrite is usually enabled by default, but double-check your config.
  • If your existing index.php has its own logic, just integrate the parseCleanUrl() function instead of replacing everything.
  • Always handle 404s—don't leave invalid routes hanging without a proper error page.
  • You can expand this function later to support more complex routing (like regex patterns for dynamic segments) if you need it.

内容的提问来源于stack exchange,提问作者Young Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:06:11