ThinkPHPHow to hide the background? The following article will introduce to you how ThinkPHP cleverly uses routing rules to hide the background, making your website more secure!

As we all know, if the backend module of the thinkphp framework is named admin, you can directly use http://domain name/admin This access method is very convenient, but it also has great security risks. Hackers can easily guess your backend and then brute force the backend. So is there any way to solve this hidden danger? Let's discuss how to use routing rules to modify the backend path to prevent hackers from knowing our backend entrance. There are many tutorials on hiding the background admin on the Internet, but the really useful one is this routing rule method.

The first step is to add setting parameters in the background that can modify the name of the background module
1,

2. The key code to save the settings is as follows:
if(request()->isPost()) {
$data=input('post.');
//获取系统全部模块名
$system_module = [];
foreach (scandir(APP_PATH) as $dir) {
if($dir == '.' || $dir == '..') {
continue;
}
if(is_dir(APP_PATH.$dir)) {
array_push($system_module, $dir);
}
}
foreach ($data as $key => $vo) {
if($key == 'admin_module' && $vo != 'admin' && in_array($vo, $system_module)) {
$this->error('后台地址不能与现有系统模块名同名');
}
}
}Notes:
- admin_module is my database The key
- APP_PATH that saves the background module name is a constant of thinkphp5.0 version. If it is other versions, please modify it yourself.
The second step is to read the configuration information of the website in application/common.php
1. The main structure of the config data table is as follows:
DROP TABLE IF EXISTS `config`; CREATE TABLE `config` ( `id` int(11) NOT NULL AUTO_INCREMENT, `key` varchar(255) DEFAULT NULL, `val` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. sysconfig($name) method: Get the corresponding value based on the key name
<?php
use think\Cache;
use app\common\model\Config;
/**
* 获取或配置系统参数
* @param string $name 参数名称
* @return string
*/
function sysconfig($name) {
$config = Cache::get('config');
if (empty($config)) {
$config = Config::column('key,val');
Cache::set('config',$config,1800);//缓存30分钟
}
return isset($config[$name]) ? $config[$name] : '';
}Supplement:
1. If it is only a system for personal use, If you don’t want to be so troublesome, you can also add the following configuration directly to config.php:
return [ // +---------------------------------------------------------------------- // | 应用设置 // +---------------------------------------------------------------------- // 后台模块名 'admin_module' => 'myadmin', ]2, and then call it directly in the project:
$admin_module = Config('admin_module');
The third step, route setting application/route.php
<?php
use think\route;
$route_config = [
'index'=>'index/index',
];
//1.获取后台模块
$admin_module = sysconfig('admin_module');
if ($admin_module == '') {
$admin_module = 'admin';
}
//2.设置后台路由
if ($admin_module != 'admin') {
$admin_route_config = [
//路由禁止:原理是把它指到非登陆地址,在没有登陆情况下,跳转到404页面;
'admin/$' => 'admin/login/jump',
'admin/login$' => 'admin/login/jump',
'admin/login/index' => 'admin/login/jump',
$admin_module . '/$' => 'admin/login/index',
];
$route_config = array_merge($route_config, $admin_route_config);
}
return $route_config;The fourth step, add the jump() method for jump verification in the login controller Login.php
1. This jump() method is actually the designated method for prohibiting routing in our third step
public function jump() {
if(!Session::has('uid')) {
$request = Request::instance();
if(sysconfig('admin_module') == 'admin' || sysconfig('admin_module') == '') {
$this->redirect('@admin/login/index');
} else {
header("HTTP/1.1 404 Not Found");
return $this->fetch(APP_PATH.'/404.html');
}
} else {
$this->redirect('@admin/index/index');
}
}2. The code in jump() above has only one function, that is If you are not logged in, accessing a prohibited route will jump to the 404 page, as follows:

3. The 404.html page is placed in the application directory, and the code is as follows :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>很抱歉,此页面暂时找不到!</title>
<style type="text/css">
body {margin: 0px; padding:0px; font-family:"微软雅黑", Arial, "Trebuchet MS", Verdana, Georgia,Baskerville,Palatino,Times; font-size:16px;}
div{margin-left:auto; margin-right:auto;}
a {text-decoration: none; color: #1064A0;}
a:hover {color: #0078D2;}
img { border:none; }
h1,h2,h3,h4 {
/* display:block;*/
margin:0;
font-weight:normal;
font-family: "微软雅黑", Arial, "Trebuchet MS", Helvetica, Verdana ;
}
h1{font-size:44px; color:#0188DE; padding:20px 0px 10px 0px;}
h2{color:#0188DE; font-size:16px; padding:10px 0px 40px 0px;}
#page{width:910px; padding:20px 20px 40px 20px; margin-top:80px;}
.button{width:180px; height:28px; margin-left:0px; margin-top:10px; background:#009CFF; border-bottom:4px solid #0188DE; text-align:center;}
.button a{width:180px; height:28px; display:block; font-size:14px; color:#fff; }
.button a:hover{ background:#5BBFFF;}
</style>
</head>
<body>
<div id="page" style="border-style:dashed;border-color:#e4e4e4;line-height:30px;">
<h1 id="抱歉-找不到此页面">抱歉,找不到此页面~</h1>
<h2 id="Sorry-nbsp-the-nbsp-page-nbsp-you-re-nbsp-trying-nbsp-to-nbsp-find-nbsp-has-nbsp-moved-nbsp">Sorry, the page you're trying to find has moved. </h2>
<font color="#666666">你请求访问的页面,暂时找不到!</font><br /><br />
<div class="button">
<a href="javascript:;" onClick="javascript :history.back(-1);" title="返回上一页">返回上一页</a>
</div>
</div>
</body>
</html>4. How to log out
public function logout() {
if(Session::has('adminid')) {
Session::delete('adminid');
}
$this->redirect(url('@'.sysconfig('admin_module')));
}Original address: https://juejin.cn/post/6981428649765371940
More programming For related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of How to configure routing in ThinkPHP to hide the background!. For more information, please follow other related articles on the PHP Chinese website!
What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PMThe article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.
How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PMArticle discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.
What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PMThe article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges
How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PMThe article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]
What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PMThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159
How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PMThe article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.
What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PMThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.
How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PMThe article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment







