Rewrite URL in PHP without htaccess

2019-08-15 05:54发布

问题:

The website is running on a web hosting where we don't have access on htaccess file.The web server is Apache. I want to rewrite URL. For example: The original URL: www.mydomainname.com/en/piecework/piecework.php?piecework_id=11 Expected URL:piecework.mydomainname.com/en/11

How to do it?

回答1:

Sadly without htaccess or apache config access, you won't be able to do this. Bug the heck out of your host or get a new one. Most of the cheapo shared hosts out there offer mod_rewrite from my experience.



回答2:

I've seen people tokenize the query string to accomplish (sort of) what you are talking about, i.e.:

domain.com/foo/bar/11

Is actually interpreted as:

domain.com/foo/bar/11.php?action=foo&query=bar

However you have to create these semantics in the physical directory structure. This is ugly, unruly to manage and much easier accomplished with mod_rewrite.

You probably have mod_rewrite enabled, here's a short tutorial to get you started.



回答3:

This code might be what you looking for: Usage: phpfile.php/en/11 Note: no mod_rewrite required.

<?php

$DEFAULT_ACTION = 'badAction';

$pathInfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
$pathParts = explode('/', substr($pathInfo, 1));
$action = isset($pathParts[0]) ? $pathParts[0] : $DEFAULT_ACTION;

if (function_exists($action)) {
    $action($pathParts);
} else {
    badAction();
}

function badAction($parts = null)
{
    print 'The function specified is invalid.';
}


function en($parts)
{
    $name = isset($parts[1]) ? $parts[1] : 'undefined';
    $xml = new SimpleXMLElement('<message>Number: ' . $name . ' </message>');
    header('Content_Type: text/xml');
    print $xml->asXML();
}


?>

ps. I found the code in 'Professional PHP6' ISBN:978-0-470-39509-7



回答4:

You could actually physically make folders/files (so the path being accessed actually physically exists) and then redirect/handle appropriately in those - unwieldy but if it's your only choice....

Another possibility would be seeing if your host will allow you at least a custom 404 error document and then handling everything in there based on the REDIRECT_URL.