PHP项目伪静态如何搭配PHP项目使用

wen PHP项目 25

本文目录导读:

PHP项目伪静态如何搭配PHP项目使用

  1. 伪静态原理
  2. 常见Web服务器配置
  3. PHP代码配合实现
  4. URL生成帮助函数
  5. 常见问题解决
  6. 实际项目示例

我来详细说明PHP项目搭配伪静态的使用方法和配置方案:

伪静态原理

伪静态是将动态URL(如 index.php?id=1)转换为看起来像静态页面(如 article/1.html)的技术,提高SEO友好性和用户体验。

常见Web服务器配置

Apache服务器(.htaccess文件)

# 开启重写引擎
RewriteEngine On
# 设置基础路径
RewriteBase /
# 伪静态规则示例
RewriteRule ^article/(\d+).html$ index.php?id=$1 [L,QSA]
RewriteRule ^category/(\w+)/page/(\d+)$ index.php?cat=$1&page=$2 [L,QSA]
RewriteRule ^product/([a-z]+)-(\d+).html$ index.php?action=product&name=$1&id=$2 [L,QSA]
# 排除真实文件或目录
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 其他请求都转发到index.php(适用于单入口框架)
RewriteRule ^(.*)$ index.php [QSA,L]

Nginx服务器配置

server {
    listen 80;
    server_name yourdomain.com;
    root /path/to/project;
    index index.php index.html;
    # 伪静态规则
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    # 自定义伪静态规则
    location /article/ {
        rewrite ^/article/(\d+).html$ /index.php?id=$1 last;
    }
    location /category/ {
        rewrite ^/category/(\w+)/page/(\d+)$ /index.php?cat=$1&page=$2 last;
    }
    # PHP处理
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

IIS服务器(web.config)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Article Rewrite" stopProcessing="true">
                    <match url="^article/(\d+).html$" />
                    <action type="Rewrite" url="index.php?id={R:1}" />
                </rule>
                <rule name="Category Rewrite" stopProcessing="true">
                    <match url="^category/(\w+)/page/(\d+)$" />
                    <action type="Rewrite" url="index.php?cat={R:1}&page={R:2}" />
                </rule>
                <rule name="Main Rule" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

PHP代码配合实现

路由解析示例

<?php
// 获取当前URL路径
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);
// 简单的路由处理
switch(true) {
    // 匹配 /article/123.html
    case preg_match('/^\/article\/(\d+)\.html$/', $path, $matches):
        $id = $matches[1];
        handleArticle($id);
        break;
    // 匹配 /category/php/page/2
    case preg_match('/^\/category\/(\w+)\/page\/(\d+)$/', $path, $matches):
        $category = $matches[1];
        $page = $matches[2];
        handleCategory($category, $page);
        break;
    // 默认路由
    default:
        handleDefault();
        break;
}

使用mvc框架(ThinkPHP示例)

// config/route.php
return [
    // 路由规则配置
    '__pattern__' => [
        'id' => '\d+',
        'name' => '\w+',
    ],
    // 伪静态路由
    'article/:id' => 'index/article/detail',
    'category/:cat/page/:page' => 'index/category/index',
    'product/:name-:id' => 'index/product/detail',
    // 强制路由
    'route_rule' => ['article', 'category', 'product'],
];

URL生成帮助函数

<?php
/**
 * 生成伪静态URL
 */
function url($action, $params = []) {
    switch($action) {
        case 'article':
            return "/article/{$params['id']}.html";
        case 'category':
            return "/category/{$params['cat']}/page/{$params['page']}";
        case 'product':
            return "/product/{$params['name']}-{$params['id']}.html";
        default:
            return "/index.php?action={$action}&" . http_build_query($params);
    }
}
// 使用示例
echo url('article', ['id' => 123]);  // /article/123.html
echo url('category', ['cat' => 'php', 'page' => 2]);  // /category/php/page/2
echo url('product', ['name' => 'book', 'id' => 456]);  // /product/book-456.html

常见问题解决

处理中文URL

// 编码处理
$name = urlencode($name);
$url = "/product/{$name}-{$id}.html";
// 解码处理
$name = urldecode($matches[1]);

分页处理

// 生成分页URL
function pageUrl($base, $page) {
    return "{$base}/page/{$page}";
}
// 处理分页请求
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

实际项目示例

项目结构

project/
├── .htaccess          # 伪静态规则
├── index.php          # 入口文件
├── router.php         # 路由处理
├── controllers/       # 控制器
├── models/           # 模型
└── views/            # 视图

完整示例代码

<?php
// router.php
class Router {
    private $routes = [];
    public function addRoute($pattern, $callback) {
        $this->routes[$pattern] = $callback;
    }
    public function dispatch($uri) {
        $uri = parse_url($uri, PHP_URL_PATH);
        foreach ($this->routes as $pattern => $callback) {
            if (preg_match($pattern, $uri, $matches)) {
                array_shift($matches); // 移除完全匹配
                return call_user_func_array($callback, $matches);
            }
        }
        // 404处理
        header("HTTP/1.0 404 Not Found");
        echo "Page not found";
    }
}
// 使用
$router = new Router();
$router->addRoute('/^\/article\/(\d+)\.html$/', function($id) {
    echo "Article ID: " . $id;
});
$router->addRoute('/^\/category\/(\w+)\/page\/(\d+)$/', function($cat, $page) {
    echo "Category: " . $cat . ", Page: " . $page;
});
$router->dispatch($_SERVER['REQUEST_URI']);

通过以上配置和代码,PHP项目就能完美配合伪静态使用,实现SEO友好的URL结构。

抱歉,评论功能暂时关闭!