I was curious to know if it was possible to somehow configure nginx so that it will parse url arguments without specifying .php at the end of the filename before the arguments are sent.
For example, let's say I have an account module which processes which aspect of the account to load, based on the argument sent. If the argument is ?sk='login', it will load the login module. If it is ?sk='register', it will load the registration module - and so on and so forth.
The problem is that when I type http://host/account?sk='login', I do not get anything via $_GET when I try to print the values within the array. The thing is that the clean URL does load the file which is supposed to manage the $_GET arguments, except it will not actually process $_GET unless I specify .php at the end of the filename.
I'm guessing there's an nginx or php-fpm configuration somehow which allows this.
Is this possible?
I figured it out:
The idea, with nginx, is to define a location, specify that location's root, and then do a try_files while specifying the $uri variable and the .php file to execute, with the arguments.
For example:
location /somelocation {
root /path/to/somelocation/on/server;
try_files $uri /somelocation/somefile.php?key=$args;
}
Rather than typing http://host/somelocation?key='someargument', you would specify /somelocation?someargument
From there on, when you call $_GET[ 'key' ] in your php, it will output someargument with a key of key. The key can be whatever you specify.
Related
I mirrored a site to local server with wget and the file names locally look like this:
comments
comments?id=123
Locally these are static files that show unique content.
But when I access second file in browser it keeps showing content from file comments and appends the query string to it ?id=123 so it is not showing content from file comments?id=123
It loads the correct file if I manually encode the ? TO %3F in browser window and I type:
comments%3Fid=123
Is there a way to fix this ? Maybe make apache stop treating ? as query separator and treat it as file name character ? Or make an URL rewrite and change ? into %3F ?
Edit: Indeed too many problems caused by ? in file name and requests. I ended up using the wget option --restrict-file-names=windows that would convert ? into an # when saving file name.
The short answer is "don't do that."
The longer answer is that ? is a reserved character in URLs, using it as a part of a filename is going to cause problems forever, and the recommended solution is to pick a different character to use in those filenames. There are many to choose from - just avoid ? & # and # and you'll probably be fine.
If you insist on keeping the file name (or if you don't have an option) try:
RewriteCond %{QUERY_STRING} (.*)
RewriteRule (.*) $1%%3F%1 [NE]
However, this is going to fire any time you have a query string, which is likely not what you want.
Is it possible, like it is for the "password" parameter in devise for example, to declare other parameters that would need to be hidden from logs ? If possible, how should it be done ?
You add any parameters you want to filter to the file config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
password is already filtered so just add any others to the array [:password,:hidden_parameter]
I'm trying to access a page from another domain, I can get all other html from php, but the files like images and audio files have relatives paths making them to be looked inside the local server whereas they're on the other server.
I've allowed cross-domain access though PHP from the other page.
header('Access-Control-Allow-Origin: *');
Then I use AJAX load to load that pages' content.
$('#local_div').load('page_to_load_on_side_B #div_on_that_page');
Now, the path looks like this:
../../user/6/535e55ed00978.jpg
But I want it to be full like.
http//:www.siteB.com/user/6/535e55ed00978.jpg
Correction: I have full access to both sites so I need to get the absolute paths from the site where these files are originating.
For this problem would use one of the following:
Server Side Approach
I would create a parameter in server B named for example abspath. When this param is set to 1 the script would start an output buffer ob_start() then before submiting would get ob contents with ob_get_clean() and finally using regular expressions make a replace of all urls for http//:www.siteB.com/. So, the script on server A would look like follows:
<?php
$abspath=(isset($_REQUEST["abspath"])?$_REQUEST["abspath"]:0);
if($abspath==1) ob_start();
// Do page processing (your actual code here)
if($abspath==1)
{
$html=ob_get_clean();
$html=preg_replace("\.\.\/\.\.\/", "http://siteb.com/");
echo $html;
}
?>
So in client side (site A) your ajax call would be:
$('#local_div').load('page_to_load_on_side_B?abspath=1#div_on_that_page');
So when abspath param is set to 1 site B script would replace relative path (note I guessed all paths as ../..) to absolute path. This approach can be improved a lot.
Client Side Approach
This replace would be done in JavaScript locally avoiding changing Server B scripts, . The replacements in Javascript would be the same. If all relative paths starts with ../.. the regex is very simple, so in site A replace $('#local_div').load('page_to_load_on_side_B #div_on_that_page'); for the following (note that I asume all relatives urls starts with ../..):
$.get('page_to_load_on_side_B #div_on_that_page', function(data) {
data=data.replace(/\.\.\/\.\.\//, 'http://siteb.com/');
$('#local_div').html(data);
});
That will do the replacement before setting html to DIV so images will be loaded from absolute URL.
Ensure full CORS access to site B.
The second approach is clean than the first so I guess would use Javascript to do the replacements, both are the same only changes where the replace is done.
There is a PHP function that can make absolute path from relative one.
realpath()
If you mean URL path, simply replace all occurences of "../" and add domain in front.
Try this one:
function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
Also you can find below solution:
In general, there are 2 solutions to this problem:
1) Use $_SERVER["DOCUMENT_ROOT"] – We can use this variable to make all our includes relative to the server root directory, instead of the current working directory(script’s directory). Then we would use something like this for all our includes:
include($_SERVER["DOCUMENT_ROOT"] . "/dir/script_name.php");
2) Use dirname(FILE) – The FILE constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:
include(dirname(__FILE__) . "/dir/script_name.php");
You may also use basename() together with dirname() to find the included scripts name and not just the name of the currently executing script, like this:
script_name = basename(__FILE__);
I personally prefer the second method over the first one, as it gives me more freedom and a better way to create a modular web application.
Note: Remember that there is a difference between using a backslash “\” and a forward (normal) slash “/” under Unix based systems. If you are testing your application on a windows machine and you use these interchangeably, it will work fine. But once you try to move your script to a Unix server it will cause some problems. Backslashes (“\”) are also used in PHP as in Unix, to indicate that the character that follows is a special character. Therefore, be careful not to use these in your path names.
I have a doubt with some of my URLs from my acces_log . There are some URLs from external sites linking me like http://domain.com/url_name.htm% (yes, with %).
Then... my server returns http error, I need to redirect this fake URLs to the correct way, and I thought in htaccess.
I only need to detect the % symbol in the last character of URL, and redirect without it.
http://domain.com/url_name.htm% --> http://domain.com/url_name.htm
How can I do this? I was trying with some samples with ? symbol but I didn't have lucky.
Thanks!
I already found the mistake...
It seems that some malformed URLs don't pass to vhost, then these petitions don't read the .htaccess.
The only way to solve this, is adding in httpd.conf the ErrorDocument 400 directive... Not is the best option for servers with different vhosts.. because all of the will have the same behaviour... but I think that is the only way for this case.
Quotation from Apache documentation:
Although most error messages can be overriden, there are certain circumstances where the >internal messages are used regardless of the setting of ErrorDocument. In particular, if a >malformed request is detected, normal request processing will be immediately halted and the >internal error message returned. This is necessary to guard against security problems >caused by bad requests.
Thanks anyway!!
This page is super helpful about the .htaccess rules.
http://www.helicontech.com/isapi_rewrite/doc/RewriteRule.htm
I saw a few solutions to this that use a small php script too. IE this one replaces #
.htaccess
RewriteRule old.php redirect.php? url=http://example.com/new.php|hash [R=301,QSA,L]
redirect.php
<?php
$new_url = str_replace("|", "#", $_GET['url']);
header("Location: ".$new_url, 301);
die;
?>
I tried everything possible, but still failed. I thought I got it at the point which I'll post
as my final attempt, but still isn't good [enough].
A script is being passed three arguments. Domain name, username and password.
But the probles is that I need domain separated in "domain" + ".com" format. Two variables.
I tried to split it using name.extension cheat, but it doesn't work quite well.
Check the simple code:
#echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.
When you try it, you get:
D:\Scripts\test>test.bat domain.com
domain
.com
D:\Scripts\test>test.bat domain.co.uk
domain.co
.uk
First obviously does work, but only because I'm able to cheat my way through.
String operations in DOS Shell are a pain in the ass. I might be able to convince
a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!
Windows ships with the Windows Scripting Host which lets you run javascript.
Change the batch file to:
#echo off
cscript //Nologo test.js %*
Create test.js:
if (WScript.Arguments.Length > 0) {
var arg = WScript.Arguments.Item(0);
var index = arg.indexOf('.');
if (index != -1) {
var domain = arg.substring(0, index);
var ext = arg.substring(index);
WScript.Echo(domain);
WScript.Echo(ext);
} else WScript.Echo("Error: Argument has no dots: " + arg);
} else WScript.Echo("Error: No argument given");
And you can use it:
C:\Documents and Settings\Waqas\Desktop>test.bat domain.com
domain
.com
C:\Documents and Settings\Waqas\Desktop>test.bat domain.co.uk
domain
.co.uk
And that does what I think you wanted.
If you want to automatize something (as stated in another answer), my solution would be to use appropriate tools. Install a Perl runtime or something else you're comfortable with. Or use the Windows power shell
Also, unless you supply your script with a list of valid top level domains, there is NO WAY, in no language, that your script can decide whether test.co.uk should be splitted as text and co.uk or test.co and uk. The only feasible possibility would be to make sure that you get only second-level-domains without sub-domain parts. Simply split at the first dot in that case.
BTW: I'm curious to why you would want to automate website creation in a Windows shell script. You aren't doing anything nasty, are you?