我想禁用不漂亮的网址,让漂亮的网址在 m 页面上工作。 例如: myexample.sk/all-posts.php - 想要禁用 myexample.sk/all-posts - 想要允许
但实际上我想将文件保留在 /_process/ 文件夹中以使其正常工作,因为网络上的所有数据都是通过 _process 文件夹中的文件处理的。
我创建了router.php
<?php
// Include the Router class file from the src folder
require_once $_SERVER['DOCUMENT_ROOT'] . '/_process/router.php';
// Initialize the router
$router = new Router();
$router->add('GET', '/all-posts', function() {
require 'all-posts.php';
});
// Dispatch the current request URL
$router->matchRoute($_SERVER['REQUEST_URI']);
这是我在同一个 _process/router.php 中的路由器类:
<?php
declare(strict_types=1);
class Router {
private array $routes = [];
// Method to add routes with HTTP method, path, and callback (function or file)
public function add(string $method, string $path, callable $callback): void {
$path = $this->normalizePath($path);
// Convert dynamic segments to a regular expression (e.g., {doctor_name} becomes a regex group)
$pathRegex = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<$1>[a-zA-Z0-9_-]+)', $path);
$this->routes[] = [
'path' => $pathRegex,
'method' => strtoupper($method),
'callback' => $callback,
];
}
// Normalize the path (removes extra slashes and ensures consistency)
private function normalizePath(string $path): string {
if ($path === '/') {
return '/';
}
$path = trim($path, '/');
return "/{$path}";
}
// Method to process the incoming request path
public function matchRoute(string $requestedPath): void {
$requestedPath = $this->normalizePath($requestedPath);
$method = strtoupper($_SERVER['REQUEST_METHOD']);
foreach ($this->routes as $route) {
// Check if method matches
if ($route['method'] === $method) {
// Check if the route pattern matches the requested path using regex
if (preg_match("#^{$route['path']}$#", $requestedPath, $matches)) {
// Extract any named parameters from the matches
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
// Call the callback and pass the parameters
call_user_func($route['callback'], $params);
return;
}
}
}
// If no matching route is found, return a 404 response
http_response_code(404);
echo "404 Not Found";
}
}
我尝试过前任。这在 htaccess 中,但此选项有效。实际上,它甚至开始将我的 example.sk/index.php 从托管提供商重新路由到 example.sk/index.html。
# Zakázať priamy prístup k PHP súborom v tomto priečinku
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
这是我的 htaccess 文件:
# Zapnutie RewriteEngine
RewriteEngine On
# Presmerovanie na 404 stranku, v pripade neexistujucej URL
ErrorDocument 404 /404.php
# Presmerovanie z www na non-www
RewriteCond %{HTTP_HOST} ^www\.example\.sk [NC]
RewriteRule ^(.*)$ http://example.sk/$1 [L,R=301,NC]
# Zabezpecenie HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Presmerovanie všetkých požiadaviek na router.php (okrem existujúcich súborov a priečinkov)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /router.php [L,QSA]
# Zabránenie zobrazeniu adresárov
Options -Indexes
# Zakázať priamy prístup k PHP súborom v tomto priečinku
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
# Zabránenie prístupu k súborom .htaccess a .htpasswd
<Files ".ht*">
Require all denied
</Files>
# Komprimácia Obsahu
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
# Nastavenie Expire Headers
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
感谢您的帮助。
为了确保漂亮的 URL 适用于您的主路由,但仍然允许访问 /process/ 文件夹中的文件,您需要调整 .htaccess 规则和路由器配置。以下是实现这一目标的方法:
您的 .htaccess 基本上是正确的,但我们可以对其进行调整,以确保 _process 文件夹中的文件在通过 router.php 路由其他所有内容时保持可访问。
# Enable RewriteEngine
RewriteEngine On
# Custom 404 page
ErrorDocument 404 /404.php
# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.example\.sk [NC]
RewriteRule ^(.*)$ http://example.sk/$1 [L,R=301,NC]
# Ensure HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Allow access to files inside /_process/ folder
RewriteCond %{REQUEST_URI} ^/_process/ [NC]
RewriteRule ^(.*)$ - [L]
# Route all other requests to router.php (except existing files and directories)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /router.php [L,QSA]
# Disable directory browsing
Options -Indexes
# Restrict direct access to PHP files, except from localhost
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
# Prevent access to .htaccess and .htpasswd
<Files ".ht*">
Require all denied
</Files>
# Enable compression for various content types
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
# Enable expiration headers for caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
1.进程文件夹排除:RewriteCond %{REQUEST_URI} ^/_process/ [NC] 行确保对 _process 文件夹内的文件的所有请求都允许绕过路由器,因此您的脚本可以按预期工作。
2.Router规则:其余请求如果不是物理文件或目录,则路由到router.php。
$router->add('GET', '/all-posts', function() {
require 'all-posts.php';
});
// You can add more routes like this:
$router->add('GET', '/about', function() {
require 'about.php';
});
如果 .htaccess 导致将 index.php 路由到 index.html 等问题,请确保您的托管提供商没有可能干扰的额外重写或索引优先级设置。您可能需要检查“默认文档”或索引优先级的托管设置,并确保 .php 文件优先于 .html。
此设置应强制执行漂亮的 URL,同时允许 _process 内的脚本按预期工作。
希望这有效:)
我找到了这个解决方案:
# Enable RewriteEngine
RewriteEngine On
# Custom 404 page
ErrorDocument 404 /404.php
# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.example\.sk [NC]
RewriteRule ^(.*)$ https://example.sk/$1 [L,R=301]
# Ensure HTTPS for all requests
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Disable directory browsing
Options -Indexes
# Prevent direct access to PHP files in _process folder
RewriteRule ^_process /.*\.php$ - [F,L]
# Route all requests to router.php (except existing files and directories)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /router.php [L,QSA]
# Restrict direct access to PHP files from the browser, except specific cases
<FilesMatch "\.php$">
# Allow access to specific PHP files or directories
RewriteCond %{REQUEST_URI} !^/router.php$ [NC]
RewriteCond %{REQUEST_URI} !^/ajax/ [NC] # Allow AJAX calls to PHP files
RewriteRule ^(.*)$ - [F,L]
</FilesMatch>
# Prevent access to .htaccess and .htpasswd files
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
# Enable compression for various content types
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
# Enable expiration headers for caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
我添加了这些部分:
# Prevent direct access to PHP files in _process folder
RewriteRule ^_process /.*\.php$ - [F,L]
# Restrict direct access to PHP files from the browser, except specific cases
<FilesMatch "\.php$">
# Allow access to specific PHP files or directories
RewriteCond %{REQUEST_URI} !^/router.php$ [NC]
RewriteCond %{REQUEST_URI} !^/ajax/ [NC] # Allow AJAX calls to PHP files
RewriteRule ^(.*)$ - [F,L]
</FilesMatch>
代替:
# Restrict direct access to PHP files, except from localhost
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>