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

如何控制用户输入地址并展示404页面?index.php前地址处理求助

处理index.php前后的未知地址,返回404页面

问题描述

当用户输入未知地址时,希望展示404页面。目前已通过PHP代码实现对index.php之后参数(如?page=xxx)的控制,但不知道如何处理index.php之前的地址部分。

已有的index.php后参数处理代码:

<?php
$pageName = 'places';
if (isset($_GET['page'])) {
$pageName = $_GET['page'];
}

$pageList = array(
    'places',
    'places_info',
    'save'
);

if (!in_array($pageName, $pageList)) {
$pageName = '404';
}
?>

解决方案:通过服务器配置处理index.php之前的地址

index.php之前的部分属于URL路径范畴,需要借助Web服务器(如Apache、Nginx)的配置拦截未知路径,统一转发到404页面或交由index.php处理。

1. Apache服务器(使用.htaccess)

在网站根目录创建.htaccess文件,添加以下规则:

# 开启重写引擎
RewriteEngine On

# 跳过已存在的文件和目录
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 方案一:将未知路径转发到index.php,由PHP统一校验
RewriteRule ^(.*)$ index.php?path=$1 [L,QSA]

# 方案二:直接返回404页面
# RewriteRule ^(.*)$ /404.php [L,R=404]

若选方案一,可在index.php中通过$_GET['path']获取前置路径,判断是否合法,不合法则返回404。

2. Nginx服务器

在站点配置文件中添加以下规则:

server {
    # 其他基础配置...

    # 匹配不存在的文件/目录
    location / {
        # 方案一:转发到index.php处理
        try_files $uri $uri/ /index.php?path=$uri;
        # 方案二:直接返回404
        # try_files $uri $uri/ =404;
    }

    # PHP处理配置(根据自身PHP版本调整)
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

补充:PHP统一校验所有未知地址

如果选择将未知路径转发到index.php,可修改代码同时校验前置路径和page参数:

<?php
$pageName = 'places';
// 处理page参数
if (isset($_GET['page'])) {
    $pageName = $_GET['page'];
}

// 校验前置路径(可根据需求添加允许的路径)
$validPaths = array('', '/');
$currentPath = $_GET['path'] ?? '';
if (!in_array($currentPath, $validPaths)) {
    $pageName = '404';
}

$pageList = array(
    'places',
    'places_info',
    'save'
);

if (!in_array($pageName, $pageList)) {
    $pageName = '404';
}

// 根据$pageName加载对应页面,例如 include "$pageName.php";
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:18:29