使用 Laravel 5 格式化 URL 查询字符串(如 Stack Overflow)
Format URL query string (like Stack Overflow) with Laravel 5
在我的 Web 应用程序中,我希望有 URLs 到帖子,就像在 Stack Overflow 中一样。例如:
http://mydomain/posts/214741/this-is-the-postname
但是当我写这样的路线时:
Route::get('post/{postid}/{postname}',array('as' => 'postlink', 'uses' => 'Post@singlePost'));
现在发生的事情如下:
1) 将此 link 粘贴到地址栏:
http://mydomain/en/post/214741/postname
2) 按回车键,由于获取请求,link 变为:
http://mydomain/en/post/214741/postname?q=post%2F214741%2Fpostname
但是,我想要的是 URL 与我粘贴它时完全一样,就是当您在浏览器中粘贴 Stack Overflow link 并单击 Enter 时发生的情况。
我需要它是一个获取请求,因为用户可以直接使用 link,因此我的控制器需要直接从中获取信息。
用 Laravel 处理这种情况的最佳方法是什么?
我的 .htaccess
文件是:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteBase /public
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ / [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ /index.php?q= [L,QSA]
</IfModule>
您好,您可以为 postName 变量添加一个模式
Route::get('/{postId}/{postName}', function($postId, $postName) {
return "$postId - $postName";
})->where('postName', '.*');
您的问题是发生在生产环境还是 Laravel 的开发服务器上?
您的 .htaccess
看起来好像已更改为将请求的 uri 作为参数 q
的查询字符串变量传递回 index.php。
而不是这个:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?q=
尝试将其改回 Laravel 附带的原始版本。
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
在我的 Web 应用程序中,我希望有 URLs 到帖子,就像在 Stack Overflow 中一样。例如:
http://mydomain/posts/214741/this-is-the-postname
但是当我写这样的路线时:
Route::get('post/{postid}/{postname}',array('as' => 'postlink', 'uses' => 'Post@singlePost'));
现在发生的事情如下:
1) 将此 link 粘贴到地址栏:
http://mydomain/en/post/214741/postname
2) 按回车键,由于获取请求,link 变为:
http://mydomain/en/post/214741/postname?q=post%2F214741%2Fpostname
但是,我想要的是 URL 与我粘贴它时完全一样,就是当您在浏览器中粘贴 Stack Overflow link 并单击 Enter 时发生的情况。
我需要它是一个获取请求,因为用户可以直接使用 link,因此我的控制器需要直接从中获取信息。
用 Laravel 处理这种情况的最佳方法是什么?
我的 .htaccess
文件是:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteBase /public
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ / [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ /index.php?q= [L,QSA]
</IfModule>
您好,您可以为 postName 变量添加一个模式
Route::get('/{postId}/{postName}', function($postId, $postName) {
return "$postId - $postName";
})->where('postName', '.*');
您的问题是发生在生产环境还是 Laravel 的开发服务器上?
您的 .htaccess
看起来好像已更改为将请求的 uri 作为参数 q
的查询字符串变量传递回 index.php。
而不是这个:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?q=
尝试将其改回 Laravel 附带的原始版本。
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]